先上代碼
<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的基本結構
<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>
在這里我們創建了一個todolist標簽作為父組件,讓它在里面循環遍歷list作為我們的輸出,同時定義了一個delete的監聽事件。
接下來在script標簽里定義子組件
Vue.component("todolist",{ props: ['content','index'], template: '<li @click="handleDelete">{{content}}</li>', methods: { handleDelete:function(){ this.$emit('delete',this.index) } } })
定義了一個全局類型的子組件,子組件的props選項能夠接收來自父組件數據,props只能單向傳遞,即只能通過父組件向子組件傳遞,這里將上面父組件的content和index傳遞下來。
將li標簽作為子組件的模板,添加監聽事件handleDelete用與點擊li標簽進行刪除。
在下面定義子組件的handleDelete方法,用this.$emit向父組件實現通信,這里傳入了一個delete的event,參數是index,父組件通過@delete監聽并接收參數
接下來是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方法實現每次點擊submit按鈕時向list里添加值,在每次添加之后將輸入框清空。
而handle方法則是點擊刪除li標簽,這里通過接受傳入的index參數來判斷點擊的是哪一個li
這是刪除前:
這是刪除后:
總結:
通過點擊子組件的li實現向外觸發一個delete事件,而父組件監聽了子組件的delete事件,執行父組件的handle方法,從而刪除掉對應index的列表項,todolist中的list對應項也會被刪除掉。
好了,以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對武林網的支持。
新聞熱點
疑難解答