国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

使用Vue父子組件通信實現(xiàn)todolist的功能示例代碼

2019-11-19 11:48:29
字體:
供稿:網(wǎng)友

先上代碼

<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>

創(chuàng)建todolist的基本結(jié)構(gòu)

<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>

在這里我們創(chuàng)建了一個todolist標簽作為父組件,讓它在里面循環(huán)遍歷list作為我們的輸出,同時定義了一個delete的監(jiān)聽事件。

接下來在script標簽里定義子組件

Vue.component("todolist",{      props: ['content','index'],      template: '<li @click="handleDelete">{{content}}</li>',      methods: {        handleDelete:function(){          this.$emit('delete',this.index)        }      }      })

定義了一個全局類型的子組件,子組件的props選項能夠接收來自父組件數(shù)據(jù),props只能單向傳遞,即只能通過父組件向子組件傳遞,這里將上面父組件的content和index傳遞下來。

將li標簽作為子組件的模板,添加監(jiān)聽事件handleDelete用與點擊li標簽進行刪除。

在下面定義子組件的handleDelete方法,用this.$emit向父組件實現(xiàn)通信,這里傳入了一個delete的event,參數(shù)是index,父組件通過@delete監(jiān)聽并接收參數(shù)

接下來是Vue實例

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)        }      }    })

handleClick方法實現(xiàn)每次點擊submit按鈕時向list里添加值,在每次添加之后將輸入框清空。

而handle方法則是點擊刪除li標簽,這里通過接受傳入的index參數(shù)來判斷點擊的是哪一個li

這是刪除前:

這是刪除后:

總結(jié):

通過點擊子組件的li實現(xiàn)向外觸發(fā)一個delete事件,而父組件監(jiān)聽了子組件的delete事件,執(zhí)行父組件的handle方法,從而刪除掉對應(yīng)index的列表項,todolist中的list對應(yīng)項也會被刪除掉。

好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,謝謝大家對武林網(wǎng)的支持。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 宣化县| 柘荣县| 南华县| 九寨沟县| 舒兰市| 吉安县| 民丰县| 夹江县| 白城市| 砚山县| 祥云县| 育儿| 南京市| 广州市| 库尔勒市| 平度市| 藁城市| 娄底市| 曲靖市| 田东县| 新津县| 新邵县| 景德镇市| 鹤岗市| 富源县| 综艺| 曲松县| 七台河市| 图们市| 辰溪县| 陇西县| 鄂伦春自治旗| 宁陵县| 唐河县| 冕宁县| 游戏| 永康市| 彩票| 武汉市| 大理市| 永昌县|