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

首頁 > 語言 > JavaScript > 正文

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

2024-05-06 15:40:50
字體:
供稿:網(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里添加值,在每次添加之后將輸入框清空。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 云浮市| 杨浦区| 保亭| 吉安县| 剑河县| 烟台市| 黎平县| 原平市| 张家口市| 卢氏县| 龙江县| 北海市| 安龙县| 高台县| 阿拉善左旗| 淳化县| 湘潭市| 七台河市| 洛扎县| 丘北县| 武鸣县| 肥乡县| 永定县| 阿合奇县| 满城县| 鄯善县| 繁昌县| 澄城县| 老河口市| 德惠市| 易门县| 开鲁县| 英山县| 茶陵县| 金华市| 龙江县| 康平县| 抚顺市| 巢湖市| 伊吾县| 德兴市|