首先在组件创建中创建子组件Todos.vue
<template>
<div class="hello">
<h1>todos show</h1>
<ul class="list-group">
<li class="list-group-item"
v-bind:class="{'complete':todo.completed}"
v-for="(todo,index) in todos">
{{todo.title}}
<button class="btn btn-warning pull-right"
v-on:click="deleteTodo(index)">
delete
</button>
<button class="btn btn-warning pull-right"
v-bind:class="[todo.completed ? 'btn-danger' :'btn-success']"
v-on:click="toggleCommpletion(todo)">
{{todo.completed?'undo':'todo'}}
</button>
</li>
</ul>
</div>
</template>
<style>
.completed {
color: darkgreen;
}
</style>
<script>
export default {
props: ['todos'],
methods: {
deleteTodo(index){
this.todos.splice(index, 1)
},
toggleCommpletion(todo){
todo.completed = !todo.completed
}
}
}
</script>要注意的是要告诉子组件有一个todos属性,就在组件中定义props属性值;
再根组件中引入子组件
import Todos from './components/Todos'
根组件中定义组件是要绑定组件属性即::todos=“todos”
<template>
<div id="app">
<img src="./assets/logo.png">
<hello></hello>
<todos :todos="todos"></todos>
</div>
</template>
<script>
import Hello from './components/Hello'
import Todos from "./components/Todos"
import TodoFrom from "./components/TodoFrom"
export default {
name: 'app',
data(){
return {
todos:[
{id:1,title:'learn vue',completed:false,}
]
}
},
computed:{
todoCount(){
return this.todos.length;
}
},
components:{
Todos,Hello,TodoFrom
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>需要注意是:data属性要定义成方法进行返回,这样子组件才能接受到