用Vue的父子组件通信实现todolist的功能
先上代碼
<body><div id="root"><div><input v-model="inputValue" /><button @click="handleClick">submit</button></div><ul><todolist v-for="(item,index) of list":key="index" :content="item":index="index"@delete="handle"></todolist></ul></div><script>Vue.component("todolist",{props: ['content','index'],template: '<li @click="handleDelete">{{content}}</li>',methods: {handleDelete:function(){this.$emit('delete',this.index)}}})new Vue({el:"#root",data: {inputValue:'',list:[]},methods: {handleClick:function(){this.list.push(this.inputValue)this.inputValue=''},handle:function(index){this.list.splice(index,1)}}})</script> </body>創建todolist的基本結構
1 <div id="root"> 2 <div> 3 <input v-model="inputValue" /> 4 <button @click="handleClick">submit</button> 5 </div> 6 <ul> 7 <todolist v-for="(item,index) of list" 8 :key="index" 9 :content="item" 10 :index="index" 11 @delete="handle" 12 ></todolist> 13 </ul> 14 </div>在這里我們創建了一個todolist標簽作為父組件,讓它在里面循環遍歷list作為我們的輸出,同時定義了一個delete的監聽事件。
接下來在script標簽里定義子組件
1 Vue.component("todolist",{ 2 props: ['content','index'], 3 template: '<li @click="handleDelete">{{content}}</li>', 4 methods: { 5 handleDelete:function(){ 6 this.$emit('delete',this.index) 7 } 8 } 9 })定義了一個全局類型的子組件,子組件的props選項能夠接收來自父組件數據,props只能單向傳遞,即只能通過父組件向子組件傳遞,這里將上面父組件的content和index傳遞下來。
將li標簽作為子組件的模板,添加監聽事件handleDelete用與點擊li標簽進行刪除。
在下面定義子組件的handleDelete方法,用this.$emit向父組件實現通信,這里傳入了一個delete的event,參數是index,父組件通過@delete監聽并接收參數
?
接下來是Vue實例
1 new Vue({ 2 el:"#root", 3 data: { 4 inputValue:'', 5 list:[] 6 }, 7 methods: { 8 handleClick:function(){ 9 this.list.push(this.inputValue) 10 this.inputValue='' 11 }, 12 handle:function(index){ 13 this.list.splice(index,1) 14 } 15 } 16 })handleClick方法實現每次點擊submit按鈕時向list里添加值,在每次添加之后將輸入框清空。
而handle方法則是點擊刪除li標簽,這里通過接受傳入的index參數來判斷點擊的是哪一個li
這是刪除前:
這是刪除后:
?
總結:通過點擊子組件的li實現向外觸發一個delete事件,而父組件監聽了子組件的delete事件,執行父組件的handle方法,從而刪除掉對應index的列表項,todolist中的list對應項也會被刪除掉。
轉載于:https://www.cnblogs.com/Filishope/p/10687844.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的用Vue的父子组件通信实现todolist的功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: https://blog.csdn.ne
- 下一篇: 设计模式(第四式:建造者模式)