vue中父子组件通信




Vue中数据应该但向流动,我们不应该在组件内部修改父组件的数据,即使修改应该通过事件通知父元素来进行修改,即子组件仅负责展示。

一个todolist的功能,的流程大概是

image

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<div id="app">
<input v-model="content"> <button @click="add">增加任务</button>
<todo :lists="todos" @remove="remove"></todo>
</div>
<script>
Vue.component('todo', {
template: '<ul><li v-for="(list, index) in lists">${list.content} <button @click="remove(index)">x</button></li></ul>',
delimiters: ['${', '}'],
props: {
lists: {
type: Array,
default: []
}
},
data () {
return {
randomColor: '#fff'
}
},
methods: {
remove: function(index) {
this.$emit('remove', index)
}
}
})
new Vue({
el: '#app',
data: {
todos: [],
content: ''
},
methods: {
add: function () {
this.todos.push({content: this.content})
},
remove: function (index) {
this.todos.splice(index, 1)
}
}
})
</script>