Vue中的组件——实现todolist的删除功能
先准备好上一讲的代码,如下:
<body>
<div id="root">
<div>
<input v-model="inputValue"/>
<button @click="handleSubmit">提交</button>
</div>
<ul>
<todo-item v-for="(item, index) of list"
:key="index"
:content="item"
>
</todo-item>
</ul>
</div>
<script>
Vue.component('todo-item', {
props: ['content'],
template: '<li @click="handleClick">{{content}}</li>',
methods: {
handleClick: function() {
alert('clicked')
}
}
})
new Vue({
el: "#root",
data: {
inputValue: '',
list: [],
},
methods: {
handleSubmit: function () {
this.list.push(this.inputValue)
this.inputValue = ''
}
}
})
</script>
</body>
之前已经在 <li> 中绑定了一个事件叫 handleClick ,我们可以在 handleClick 中实现子组件的删除。首先要清楚,子组件的显示与否取决于父组件里面 list 的数据,所以如果我们想要实现子组件的删除,我们必须在父组件里面把子组件对应的数据给删除掉。
因为要通知父组件要删除哪一个子组件,所以还需要获取子组件的下标。
<ul>
<todo-item v-for="(item, index) of list"
:key="index"
:content="item"
:index="index"
>
</todo-item>
</ul>
<script>
Vue.component('todo-item', {
props: ['content', 'index'],
template: '<li @click="handleClick">{{content}} {{index}}</li>',
methods: {
handleClick: function () {
}
}
})
</script>
当子组件被点击的时候要通知父组件把数据删除,我们可以使用 $emit 方法并传入事件名称来触发一个事件通知父组件。
当点击子组件时触发一个叫 delete 的自定义事件,并将子组件的下标传给父组件。
<script>
Vue.component('todo-item', {
props: ['content', 'index'],
template: '<li @click="handleClick">{{content}} {{index}}</li>',
methods: {
handleClick: function () {
this.$emit('delete', this.index)
}
}
})
</script>
监听子组件事件:
Vue 实例提供了一个自定义事件的系统来解决这个问题。父级组件可以像处理 native DOM 事件一样通过
v-on(@)
监听子组件实例的任意事件(delete):
<ul>
<todo-item v-for="(item, index) of list"
:key="index"
:content="item"
:index="index"
@delete="handleDelete">
</todo-item>
</ul>
在我们开发
<todo-item>
组件时,它的一些功能可能要求我们和父级组件进行沟通。例如我们希望添加的列表中的某一项点击后可以被删除,同时让列表中的其他项任然保留。在其父组件中,我们可以通过添加一个
handleDelete
方法来支持这个功能:实验:
可以发现每次点击都会触发
handleDelete
方法,并显示子组件的下标。
<script>
new Vue({
el: "#root",
data: {
inputValue: '',
list: [],
},
methods: {
handleSubmit: function () {
this.list.push(this.inputValue)
this.inputValue = ''
},
handleDelete: function (index) {
// alert(index)
this.list.splice(index, 1)
}
}
})
</script>
视频学习地址: 课程介绍,vue2.5入门 教程-慕课网 (imooc.com)