文章目录
一、slot 基本用法
插槽指允许将自定义的组件像普通标签一样插入内容
import Vue from 'vue'
// 定义组件componentOne
const compoentOne = {
template: `
<div :style="style1">
<slot></slot> // 定义插槽
</div>
`,
data () {
return {
style1: {
width: '200px',
height: '200px'
border: '1px solid #ccc'
}
}
}
}
调用组件
new Vue({
components: {
ComOne: componentOne
},
el: '#id',
data () {
return {
val1: '123'
}
},
template: `
<div>
<com-one>
<span>{{val1}}</span> // 使用插槽
</com-one>
</div>
`
})
二、具名插槽
给具体的插槽命名,并在使用的时候传入插槽的名称
import Vue from 'vue'
// 定义组件componentOne
const compoentOne = {
template: `
<div :style="style1">
<div>
<slot name="header"></slot> // 定义一个名称为header的插槽
</div>
<div>
<slot name="body"></slot> // 定义一个名称为body的插槽
</div>
</div>
`,
data () {
return {
style1: {
width: '200px',
height: '200px'
border: '1px solid #ccc'
}
}
}
}
调用组件
new Vue({
components: {
ComOne: componentOne
},
el: '#id',
data () {
return {
val1: '123',
val2: '456'
}
},
template: `
<div>
<com-one>
<span slot="header">{{val1}}</span> // 使用插槽'header**重点内容**'
<span slot="body">{{val2}}</span> // 使用插槽'body'
</com-one>
</div>
`
})
三、作用域插槽
将定义插槽的变量作用域到使用插槽中
import Vue from 'vue'
// 定义组件componentOne
const compoentOne = {
template: `
<div :style="style1">
<slot :aa="val1" :bb="val2"></slot> // 给插槽传入变量
</div>
`,
data () {
return {
style1: {
width: '200px',
height: '200px'
border: '1px solid #ccc'
},
val1: 'slot1',
val2: 'slot2'
}
}
}
调用组件
new Vue({
components: {
ComOne: componentOne
},
el: '#id',
data () {
return {
val1: '123'
}
},
template: `
<div>
<com-one>
<span slot-scope="props">{{props.aa}}{{props.bb}}{{val1}}</span> // 定义插槽传入的对象props,并使用
</com-one>
</div>
`
})
vue2.6以后对具名插槽和作用域插槽做了修改,但任然没有废弃之前语法
四、具名插槽(2.6以后)
有时候我们希望在指定的位置输出我们的子元素,这时候具名插槽就排上了用场。
<!--组件调用时-->
<MyFooter>
<template v-slot:footer>
<!--这里v-slot:后边的值与组件内的slot的name属性对应,也就是插槽的名称。-->
<div>list</div>
</template>
</MyFooter>
<!--书写组件时-->
<template>
<div>
{{age}}
<div>
<slot name='footer' />
<!--这里name的值就是这个插槽的名称。-->
</div>
</div>
</template>
最后我们会在我们想要的位置将我们的元素放置。
五、作用域插槽(vue2.6以后)
作用域插槽的主要作用是在书写插槽内容时可以获取到插槽作用域的值。
<!--组件调用-->
<ul>
<myli>
<template v-slot:footer="message">
<div>{{message.aa}}</div>
</template>
</myli>
</ul>
<!--书写组件时-->
<template>
<li>
<slot name='footer' :aa="title">
</slot>
</li>
</template>
注意事项:
这里需要注意的是message是所有你绑定属性的集合,也就是你写的:aa=“title”会当做message的属性来实现。当然这里message可以换做其它的名称。
还可以作为组件通讯来回答
总结
v-slot的出现是为了代替原有的slot和slot-scope
简化了一些复杂的语法。
一句话概括就是v-slot :后边是插槽名称,=后边是组件内部绑定作用域值的映射。
Slot插槽
插槽就是父组件往子组件中插入一些内容。
有三种方式,默认插槽,具名插槽,作用域插槽
- 默认插槽就是把父组件中的数据,显示在子组件中,子组件通过一个slot插槽标签显示父组件中的数据
- 具名插槽是在父组件中通过slot属性,给插槽命名,在子组件中通过slot标签,根据定义好的名字填充到对应的位置。
- 作用域插槽是带数据的插槽,子组件提供给父组件的参数,父组件根据子组件传过来的插槽数据来进行不同的展现和填充内容。在标签中通过slot-scope来接受数据。