Vue 实现了一套内容分发的 API,将 元素作为承载分发内容的出口。
实例:
最终实现效果的普通代码:
<div id="app">
<p>学习列表</p>
<ul>
<li>Java</li>
<li>Linux</li>
<li>Python</li>
</ul>
</div>
使用slot插槽实现,并实现后边删除按钮,删除选择的目标:
<body>
<!--View层 视图-->
<div id="app">
<father>
<!--下面两个组件,代替的是father组件里面的slot插槽-->
<son1 slot="fatherSon1" :titleSon="title"></son1>
<son2 slot="fatherSon2" v-for="(itemFor.indexFor) in items"
:itemSon="itemFor" :indexSon="indexFor" @remove="removeItems(indexFor)" :key="indexFor"></son2>
</father>
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script>
//slot:插槽,定义组件Vue.component("方法名",{方法体});
//template中的\是反转义符,跟加引号是一样的效果
//类似<div> <slot name="son1"></slot> <ul> <slot name="son2"></slot> </ul> </div>'
Vue.component("father",{
template:'<div>\
<slot name="fatherSon1"></slot>\
<ul>\
<slot name="fatherSon2"></slot>\
</ul>\
</div>'
});
Vue.component("son1",{
props:["titleSon"],
template:'<div>{{titleSon}}</div>'
});
Vue.component("son2",{
props:['itemSon','indexSon'],
//绑定点击事件v-on,只能绑定组件内的点击事件(方法)
template:'<li>{{itemSon}} <button @click="remove">删除</button></li>',
methods:{
remove:function(index){
//this.$emit 自定义事件
this.$emit('remove',index);
}
}
});
var vm = new Vue({
el: "#app",
data:{
title:"吉吉讲课",
items:['Jave','Linux','Python']
},
methods:{
removeItems:function(index){
console.log("删除了-"+this.items[index]+"-ok!");
this.items.splice(index,1);//当前下标,删除一个数
}
}
});
</script>
</body>