在 Vue 中我们使用 元素,作为承载分发内容的出口,可以应用在组合组件的场景中。
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
</head>
<body>
<div id="app">
<todo>
<todo-title slot="todo-title" title="啦啦啦"></todo-title>
<todo-items slot="todo-items" v-for="(item,index) in todoItems" v-bind:item="item" v-bind:index="index"></todo-items>
</todo>
</div>
<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>'
});
//这里的index,就是数组的下标
Vue.component('todo-items',{
props: ['item','index'],
template:'<li>{{index + 1}}.{{item}}</li>'
});
new Vue({
el:'#app',
data:{
todoItems:['111','222','333']
}
})
</script>
</body>
</html>
我们的 todo-title 和 todo-items 组件分别被分发到了 todo 组件的 todo-title 和 todo-items 插槽中