https://codesandbox.io/s/vue-todo-list-app-with-single-file-component-vzkl3?file=/src/App.vue:0-1551
下载代码
npm install
npm run dev
即可
两个代码
app.vue
<template>
<div class="wrapper">
<h1>My Todo List</h1>
<form @submit.prevent="addTodo">
<input type="text" name="todo-text" v-model="newTodoText" placeholder="New todo">
</form>
<ul v-if="todos.length">
<TodoItem v-for="todo in todos" :key="todo.id" :todo="todo" @remove="removeTodo"/>
</ul>
<p class="none" v-else>Nothing left in the list. Add a new todo in the input above.</p>
</div>
</template>
<script>
import TodoItem from "./TodoItem.vue"
let nextTodoId = 1
const createTodo = text => ({
text,
id: nextTodoId++
})
export default {
components: {
TodoItem
},
data() {
return {
todos: [
createTodo("Learn Vue"),
createTodo("Learn about single-file components"),
createTodo("Fall in love ❤️")
],
newTodoText: ""
}
},
methods: {
addTodo() {
const trimmedText = this.newTodoText.trim()
if (trimmedText) {
this.todos.push(createTodo(trimmedText))
}
this.newTodoText = ""
},
removeTodo(item) {
this.todos = this.todos.filter(todo => todo !== item)
}
}
}
</script>
<style lang="stylus">
*, *::before, *::after
box-sizing border-box
html, body
font 16px/1.2 BlinkMacSystemFont, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif
padding 10px
.wrapper
width 75%
margin 0 auto
form
margin-bottom 20px
input[type="text"]
width 100%
padding 10px
border 1px solid #777
ul, li
margin 0
padding 0
p.none
color #888
font-size small
</style>
TodoItem.vue
<template>
<li>
<span>{{ todo.text }}</span>
<button @click.prevent="$emit('remove', todo)">Remove</button>
</li>
</template>
<script>
export default {
props: {
todo: {
required: true,
type: Object
}
}
}
</script>
<style lang="stylus" scoped>
li
display flex
margin 5px 0
span
flex 1
button
border 1px solid orange
background orange
color white
font-size 0.8rem
padding 2px 4px
cursor pointer
&:hover
border-color #ff8100
background #ff8100
</style>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Vue Simple Todo App with SFC</title>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css"
/>
<link rel="stylesheet" href="/dist/main.css" />
<link id="external-css" rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" media="all">
</head>
<body>
<div id="app"></div>
<script src="/dist/main.js"></script>
</body>
</html>
main.js
不变