插槽slot
一、基本使用
使组件具备扩展性
<div id = 'app'>
<cpn1><p>11111</p></cpn1>
<cpn1><button>按钮</button></cpn1>
</div>
<template id = 'cpn'>
<div>
<h2>我是标题</h2>
<p>我是子组件</p>
<slot></slot>
</div>
</template>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
components: {
cpn1: {
template: cpn
}
}
})
</script>
- 插槽内可以通过
<slot><buttion>按钮<button></slot>
的方式定义默认值 - 插槽内可以传入多个标签
二、具名插槽
具有name属性的插槽,方便调用,在使用插槽的时候加入slot=""属性,可以替换对应name的插槽
<div id = 'app'>
<cpn1>
<button slot="left">按钮</button>
<span slot="right">返回</span>
</cpn1>
</div>
<template id = 'cpn'>
<div>
<h2>我是标题</h2>
<p>我是子组件</p>
<slot name="left"><span>左边</span></slot>
<slot name = "medd"><span>中间</span></slot>
<slot name="right"><span>右边</span></slot>
</div>
</template>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
components: {
cpn1: {
template: cpn
}
}
})
</script>
三、作用域插槽
父模板的所有东西都会在父模板内进行编译,子模板里的所有东西都会在子模板内进行编译。
作用于插槽:父组件提供插槽的标签,但是内容有子组件提供
- 在自定义模板中用插槽属性如:aaa,接收子组件数据
- 在父组件中调用子组件的位置增加标签,新版本也可以用其他标签,并在标签中使用slot-scope属性绑定子组件模板中的aaa属性,即获取子组件数据。
<div id = 'app'>
<cpn1></cpn1>
<cpn1>
<template slot-scope="slot">
<span>{{slot.abc.join(" - ")}}</span>
</template>
</cpn1>
<cpn1></cpn1>
</div>
<template id = 'cpn'>
<div>
<slot :abc="message">
<div>
<ul>
<li v-for = "item in message">{{item}}</li>
</ul>
</div>
</slot>
</div>
</template>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data:{
message1: "你好呀"
},
components: {
cpn1: {
template: cpn,
data () {
return {
message: ["aaaa",'bbbb','cccc','dddd']
}
}
}
}
})
</script>