日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

用Vue的父子组件通信实现todolist的功能

發布時間:2024/4/17 vue 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用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的功能的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。