<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>todolist组件拆分2</title> <script src="../2.5.20-vue.js"></script> <!--//提前加载,避免出现抖屏--> </head> <body> <!--两大核心 父组件和子组件的交互 父组件通过props的方式向子组件传递参数 props: ['content', "index"], //接收两个属性值 子组件通过发布订阅模式来向父组件传递参数 this.$emit('delete', this.index) --> <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" :index = "index" @delete = "handleDelete" ></todo-item> <!-- @delete = "handleDelete"指的是todo-item的方法 子组件发布这个事件,父组件恰好定义好了这个事件,那么子组件就可以通过发布订阅的方式定义这个事件了 --> </ul> </div> <script> Vue.component("todo-item", { /* 在vue中父组件通过向子组件传值是通过属性的方式进行的*/ props: ['content', "index"], //接收两个属性值 template: '<li @click="handleClick">{{content}}{{index}}</li>', methods: { handleClick(){ this.$emit('delete', this.index) } } }); /* var TodoItem = { //局部变量定义的组件 template: '<li>item</li>' }*/ new Vue({ el: '#root', /**创建vue的实例,接管id等于root的内容*/ /*如果你不定义component那么它会把root下面的内容当作component的内容*/ data: { inputValue: "", list: [] }, methods: { handleSubmit(){ this.list.push(this.inputValue) this.inputValue = '' }, handleDelete(index){ console.log(this.list); this.list.splice(index, 1) } }, }) </script> </body> </html>
父组件和子组件的交互以及实现todolist的删除功能
猜你喜欢
转载自blog.csdn.net/xuxinwen32/article/details/86673978
今日推荐
周排行