先上代碼
<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)的支持。
新聞熱點
疑難解答