持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情
1. 内容分发(插槽)
在Vue.js中我们使用<slot></slot>
元素作为承载分发内容的出口,可以称其为插槽,可以应用在组合组件的场景中
<div id="app">
<todo>
<todo-title slot="todo-title" ******:** title="title"></todo-title>
<todo-items slot="todo-items" v-for="item in todoItems" :item="item"></todo-items>
</todo>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script>
//slot插槽
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: ['item'],
template: '<li>{{item}}</li>'
});
var vm = new Vue({
el: "#app",
data:{
title:"列表",
todoItems:['java','前端','python']
}
});
</script>
2. 自定义事件
组件化:
组合组件 slot插槽
组件内部绑定事件需要用到 this.$emit(“自定义事件名”,参数);
数据项在vue的实例中,但删除操作要在组件中完成,那么组件如何删除Vue实例中的数据?此时就涉及到参数传递与事件分发了, Vue为我们提供了自定义事件的功能很好的帮助我们解决了这个问题; 组件中使用this.$emit(‘自定义事件名’, 参数) ,而在视图层通过自定义事件绑定Vue中的删除操作的方法
<div id="vue">
<todo>
<todo-title slot="todo-title" :title="title"></todo-title>
<todo-items slot="todo-items" v-for="(item,index) in todoItems"
:item="item" :index="index" v-on:remove="removeItems(index)"></todo-items>
<!-- v-on自定义事件-->
</todo>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script type="text/javascript">
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>'
});
//这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来!
Vue.component("todo-items",{
props:["item","index"],
template:"<li>{{index}}---{{item}} <button @click='remove'>删除</button></li>",
//只能调用到当前组件的方法,调用不到外面的removeItems方法
methods: {
remove: function (index) {
// $emit能将该方法绑定到v-on:remove
//this.$emit(“自定义事件名”,参数);
this.$emit('remove');
}
}
});
var vm = new Vue({
el:"#vue",
data:{
title:"study",
todoItems:['java','前端','Python']
},
methods: {
removeItems: function (index) {
console.log("删除了"+this.todoItems[index]+" ok");
this.todoItems.splice(index,1);
}
}
});
</script>
todo-items组件中的methods只能调用到当前组件的方法,调用不到外面的removeItems方法
因此,使用this.$emit('remove');
将该方法绑定到v-on:remove上,实现删除功能。
实现效果如下:
删除其中一项,前面的数字会自动变化
如,删除java