# 插槽

插槽 (Slot) 是 vue 为组件的封装者提供的能力。允许开发者在封装组件时,把不确定的,希望用户指定的部分定义为插槽

  • vue 官方规定:每个 slot 插槽,都要有个 name 名称
  • 如果省略了 slot 的 name 属性,则有一个默认名称,为 default
  • 如果要把内容填充到指定名称的插槽中,需要使用 v-slot: 这个指令
  • v-slot: 后面要跟上插槽的名字
  • v-slot: 指令不能直接用在元素身上,必须用在 template 标签上
  • template 是一个虚拟的标签,只起到包裹性的作用,但是不会被渲染为任何实质性的 html 元素
  • v-slot: 的简写形式为 #
1
2
3
4
5
6
7
8
<Left>
<template v-slot:context1>
<p>hello world</p>
</template>
<template #context2>
<p>这是context2内容中的插槽</p>
</template>
</Left>

# 作用域插槽

在封装组件时,未预留的提供属性对应的值,这种用法,叫做 “作用域插槽”

1
2
3
4
5
6
7
// App.vue
<template #content="obj">
<p>{{obj}}</p> //输出 : {"msg": "hello vue.js"}
</template>

//Article.vue
<slot name="content" msg="hello vue.js"></slot>

# 作用域插槽解构赋值

当 slot 含有多个属性的时候,可以使用结构赋值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// App.vue
<template #content="{msg, user}">
<p>{{msg}}</p> // 输出 hello vue.js
<p>{{user}}</p> // 输出 {"name": "zs", "age": 20}
</template>

//Article.vue
<slot name="content" msg="hello vue.js" :user="userinfo"></slot>

data() {
return {
userinfo: {
name: 'zs',
age: 20
}
}
}
更新于 阅读次数