先上代码
<!DOCTYPE html> <html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8"> <title>vue中使用插槽板</title> <style> [v-cloak]{ display: none; } </style> </head> <body> <!-- vue模板 --> <div id="sloter" v-cloak> <!--使用插槽板--> <slots> <slots-titles slot="slots-titles" :title="title"></slots-titles> <slots-contents slot="slots-contents" v-for="(content,contentNumber) in contents" :content="content" :number="contentNumber" v-on:remove-diy="removeItem(contentNumber)" :key="contentNumber"></slots-contents> </slots> </div> <!--导入vue--> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script> /*先定义”插槽板“-slots*/ Vue.component("slots",{ /*定义插槽板的格式,并在插槽板中设置两个槽口*/ template:'<div>\ <slot name="slots-titles"></slot>\ <ul>\ <slot name="slots-contents"></slot>\ </ul>\ </div>' }); /*编辑两个符合槽口的插卡*/ Vue.component("slots-titles",{ /*接收入参*/ props:["title"], /*将入参注入在插槽中*/ template:'<div>{{title}}</div>' }); Vue.component("slots-contents",{ props:["content","number"], template:'<li>{{content}} <button @click="remove">点我删除!</button></li>', methods:{ /*接收入参index*/ remove:function (index) { /*this.$emit()调用的方法不能使用驼峰命名法命名*/ this.$emit("remove-diy",index) } } }); var vm = new Vue({ el: "#sloter", data:{ title:"槽口一的数据注入", contents:["槽口二的数据注入0","槽口二的数据注入1"] }, methods:{ removeItem:function (index){ this.contents.splice(index,1) } } }); </script> </body> </html>
注解:
解释一下为什么插槽中要使用:key
引用简书上作者Nanshannan的一句话(原文地址:https://www.jianshu.com/p/4bd5e745ce95)