以删除todolist的组件里面的item来做相应的传值 主要的思想就是通过子组件发出信号通知父组件,父组件再对数据进行相应的操作
组件中定义index属性用来作为item的索引因为组件是没有数据的,所以得通过绑定方法,然后发送消息给父组件,让父去删除对应的数据具体代码实现如下,实现的具体功能就是点击todolist的item,然后会对item进行删除
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>TodoList</title> <script src="./vue.js"></script> </head> <body> <div id="root"> <input type="text" v-model="inputValue" /> <button v-on:click="handleBtnClick">提交</button> <ul> <todo-item v-bind:content="item" v-bind:index="index" v-for="(item, index) in list" v-on:delete="handleItemDelete"></todo-item> </ul> </div> <script> var TodoItem = { props: ['content', 'index'], template: "<li @click='handleItemClick'>{{content}}</li>", methods: { handleItemClick: function () { this.$emit("delete", this.index); } } } var app = new Vue({ el: '#root', components: { TodoItem: TodoItem }, data: { list: [], inputValue: '' }, methods: { handleBtnClick: function () { this.list.push(this.inputValue) this.inputValue = '' }, handleItemDelete: function (index) { this.list.splice(index, 1) } } }) </script> </body> </html>以上代码还有部分可以优化的部分
v-bind:content="item"可以优化简写成
:content="item" v-on:delete="handleItemDelete">可以优化简写成
@delete="handleItemDelete">