Vue插槽與刪除按鈕
阿新 • • 發佈:2021-06-17
<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>
刪除總結:首先在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" 不用在傳值了。