之前的文章中我们实现了父组件向子组件传值,这篇文章我们将实现子组件向父组件传值。
之前我们可以向TodoList中添加数据项,这篇文章我们将学习如何删除一个列表项。
实现代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>TodoList</title> <script src="./vue.js"></script> </head> <body> <div id="app"> <input type="text" v-model="inputTxt"> <button @click="submitEvent">提交</button> <ul> <todo-item v-bind:content="list" @delete="handleItemClick" v-bind:index="index" v-for="(list,index) in todoList" ></todo-item> </ul> </div> <script> //子组件 let TodoItem = { props: ['content','index'], template: `<li @click="todoItemClick">{{this.content}}</li>`, methods: { todoItemClick: function(){ this.$emit('delete',this.index); } } }; var app = new Vue({ el: '#app', data:{ inputTxt:'', todoList: [] }, methods:{ submitEvent: function(){ this.todoList.push(this.inputTxt); this.inputTxt = ''; }, handleItemClick: function (index) { this.todoList.splice(index,1); } }, components:{ TodoItem: TodoItem } }) </script> </body> </html>
我们使用$emit向父组件触发事件,子组件触发的事件,父组件恰好监听,监听过后就能获取到子组件带出来的内容,实现子组件向父组件传值。
父组件向子组件传值,我们使用v-bind的方式向子组件传递,子组件需要使用props组件一下。