<div id="app"> <todo> <todo-title slot="todo-title" v-bind:title="title"></todo-title> <todo-items slot="todo-items" v-for="(item,index) in items" v-bind:item="item" v-bind:index="index" v-on:remove="removeItems"></todo-items> </todo> </div> <script type="text/javascript"> //定義組件todo是組件名稱 Vue.component("todo", { template: ' <div><slot name=\'todo-title\'></slot><ul><slot name=\'todo-items\'></slot></ul></div>'//模板 }); Vue.component("todo-title",{ props: ['title'], template: '<div>{{title}}</div>' }); Vue.component("todo-items",{ props: ['index', 'item'], template: "<li>{{index}}---{{item}}<button @click='remove'>刪除</button></li>", methods:{ remove: function () { this.$emit("remove") 第一步 } } }) var vue = new Vue({ el: "#app", data: { title: '標題!', items: ["迪麗熱巴", "楊冪", "劉亦菲"] } , methods: { removeItems: function (index) { this.items.splice(index, 1) 第二步 } } }) </script>
插槽的核心內涵就是,只不過slot是插槽標識而已。
<div id="todo"> <div id="todo-title"> 標題 </div> <ul id="todo-items"> <li>111</li> <li>111</li> <li>111</li> </ul> </div>
1、父組件可以使用 props 把數據傳給子組件。
2、子組件可以使用 $emit 觸發父組件的自定義事件。
vm.$emit( event, arg ) //觸發當前實例上的事件
vm.$on( event, fn );//監聽event事件后運行 fn;
刪除總結:首先在Vue.component定義組件里面是不能直接調取 var vue = new Vue 里的方法的,必須要間接的調取數據。
通過第一步的方法調取到第二步的方法。
注意1:在自定義組件里要先綁定 v-on:remove="removeItems" 第一步的 remove 方法 然后到第二步 removeItems
方法,因為只有這樣 <button @click='remove'>刪除</button> 刪除按鈕里綁定的 remove 事件才能在自定義組件里
找到。總之就是先寫 remove 方法,然后再 button 里綁定該方法,我們為了能夠在自定義組件里響應該方法,需要
進行 v-on:remove 的一個綁定,這一就能夠找到 removeItems 第二步中的方法。
注意2:在removeItems 里需要傳一個參數 index 就是編號(removeItems: function (index))而該參數在
v-for="(item,index) in items" 已經自動的傳入了,所以在 v-on:remove="removeItems" 不用在傳值了。
