插槽内可以包含任何模板代码,包括 HTML,甚至其它的组件。
在插槽中使用数据:
<div id="todo-list-example">
<todo-item>
<p>My name is{{message}}</p> //数据为父组件中的数据
</todo-item>
</div>
<script>
Vue.component('todo-item', {
template:`
<div>
<p>hello</p>
<slot></slot>
</div>
`
})
new Vue({
el: '#todo-list-example',
data:{
message:'Wenmeichao'
}
})
</script>
插槽中可以给默认数据
<div id="todo-list-example">
<todo-item>
Save //父组件提供了插槽内容就会显示父组件提供的
</todo-item>
</div>
<script>
Vue.component('todo-item', {
template:`
<div>
<button type="submit">
<slot>Submit</slot> //当父组件使用子组件并且不提供任何插槽内容时显示
</button>
</div>
`
})
new Vue({
el: '#todo-list-example',
data:{
message:'Wenmeichao'
}
})
</script>
具名插槽
注意
v-slot
只能添加在<template>, v-slot:header 可缩写成 #header
<div id="todo-list-example">
<todo-item title="wenmeichao">
<template v-slot:header>
<h1>world</h1> //具名插槽定义后只有通过 name 引用才会显示
</template>
<h1>world2</h1>
</todo-item>
</div>
<script>
Vue.component('todo-item', {
props: ['title'],
template:` //模板template有且只有一个根元素
<div>
<slot name="header"></slot> //具名插槽的引用
<p>Hello</p>
<slot>{{title}}</slot> //插槽内可以存放默认值,当父组件未传递任何DOM结构时显示。可以是数据、字符串、html标签
</div>
`
})
new Vue({
el: '#todo-list-example'
})
</script>
插槽只有一个,但是具名插槽可以有多个。
作用域插槽
作用域插槽:让插槽访问子组件中的数据。
<div id="todo-list-example">
<todo-item>
<template v-slot:default="scope"> //scope存放接收的数据,可自定义命名 default为默认插槽的名称
<h3>{{scope.info}}--hello</h3>
</template>
</todo-item>
</div>
<script>
Vue.component('todo-item', {
data: function(){
return{
list:['one','two','three','four']
}
},
template:`
<div>
<slot v-for="item in list" :info="item"></slot> info 称为插槽prop
</div>
`
})
new Vue({
el: '#todo-list-example'
})
</script>
以上。