1 <!DOCTYPE HTML> 2 <html lang="zh"> 3 <head> 4 <meta charset="utf-8" /> 5 <title>Vue</title> 6 <script src="../../vue.js"></script> 7 </head> 8 <body> 9 <!-- --------------------------------------Mr丶L----------------------------------------------- --> 10 <!-- todoList 删 除 功 能--> 11 <div id="root"> 12 <div> 13 <input v-model="inputValue" /> 14 <button @click="add">提交</button> 15 <ul> 16 <todo-item 17 v-for="(item,index) of list" 18 :key="index" 19 :content="item" 20 :index="index" 21 @delete="handelDelete" <!--父组件订阅--> 22 > 23 </todo-item> 24 </ul> 25 </div> 26 </div> 27 <!-- --------------------------------------Mr丶L----------------------------------------------- --> 28 <script> 29 // 全局组件 30 Vue.component('todo-item',{ 31 props:['content','index'], //接收属性的值 32 template:'<li>item</li>' 33 }) 34 //局部组件 35 var TodoItem ={ 36 props:['content'], 37 template:'<li @click="handelClick">{{content}}</li>', 38 methods:{ 39 handelClick:function(){ 40 this.$emit('delete',this.index) //子组件发布 41 } 42 } 43 } 44 //----就近原则,此处执行局部组件 45 46 new Vue({ 47 el:"#root", 48 components:{ //局部组件的注册声明 49 'todo-item':TodoItem 50 }, 51 data:{ 52 inputValue:'', 53 list:[] 54 }, 55 methods:{ 56 add:function () { 57 this.list.push(this.inputValue) //添加 58 this.inputValue='' //置空 59 }, 60 handelDelete:function(index){ 61 /* 62 splice(index,len,[item])它也可以用来替换/删除/添加数组内某一个或者几个值(该方法会改变原始数组) 63 index:数组开始下标 64 len: 替换/删除的长度 65 item:替换的值,删除操作的话 item为空 66 */ 67 this.list.splice(index,1); 68 69 } 70 71 } 72 73 }) 74 </script> 75 76 </body> 77 </html>