自定義事件內容分發
阿新 • • 發佈:2022-03-04
參考連結:https://blog.csdn.net/Jzandth/article/details/108781704
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <todo> <todo-title slot="todo-title" :title="titleName"></todo-title> <todo-book slot="todo-book" v-for="(books,indexs) in bookName" :book="books" v-bind:index="indexs" v-on:rmv="r(indexs)" :key="indexs"></todo-book> </todo> </div> <!--匯入Vue--> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script> <script> Vue.component("todo",{ template:'<div>' + '<slot name="todo-title" ></slot>'+ '<ul>'+ '<slot name="todo-book"></slot>'+ '</ul>'+ '</div>' }); Vue.component("todo-title",{ props: ['title'], template:'<div>{{title}}</div>' }); Vue.component("todo-book",{ props:['book','index'], template:'<li>{{index}}---{{book}} <button @click="rmv">刪除</button></li>', methods: { rmv: function(index){ this.$emit('rmv',index);//this.$emit()自定義事件分發 } } }); var vm=new Vue({ el: "#app", data:{ titleName:"四大名著", bookName:['水滸傳','西遊記','三國演義','紅樓夢'] }, methods:{ r: function(index){ this.bookName.splice(index,1);//一次刪除一個元素 } } }); </script> </body> </html>