VUE 父子组件互相传值
2019-02-09 本文已影响11人
MccReeee
父组件代码
var app = new Vue({
el: "#root",
components: {
TodoItem: TodoItem,
},
data: {
todoValue: "",
list: []
},
methods: {
handleBtnClick: function () {
this.list.push(this.todoValue)
//添加完后清空输入框
this.todoValue = ""
},
handleItemDelete: function (index) {
this.list.splice(index, 1)
}
}
})
子组件代码
//这是局部组件的写法
var TodoItem = {
props: ["content", "index"],
template: "<li @click='handleItemClick'> {{content}}</li>",
methods: {
handleItemClick: function () {
this.$emit("delete", this.index)
}
}
}
- 父组件向子组件传值 通过
v-bind:
<todo-item
v-bind:content="item"
v-bind:index="index"
v-for="(item,index) in list"
@delete="handleItemDelete">
</todo-item>
- 子组件向父组件传值 通过事件绑定,比如这个
@delete=handleItemDelete
,并在父组件中实现handleItemDelete
this.$emit("delete", this.index)
methods: {
handleBtnClick: function () {
this.list.push(this.todoValue)
//添加完后清空输入框
this.todoValue = ""
},
handleItemDelete: function (index) {
this.list.splice(index, 1)
}
}