插槽
        
 # 作用域插槽
作用域插槽是 vue.js 中一个很有用的特性,可以显著提高组件的通用性和可复用性。但是他实在不太好理解,要尝试搞清楚父子作用域之间错综复杂的关系是很困难的一件事(对我来说是这样)。
有时候,我们需要让插槽内容访问子组件的数据。但是,我们知道插槽并不能访问到子组件的作用域,也就拿不到子组件中的数据。这时作用域插槽的功能就体现出来了,我们可以通过作用域插槽来获取子组件的数据。
# 使用方法
作用域内的插槽允许我们父组件中的插槽内容访问仅在子组件中找到的数据。 例如,我们可以使用作用域限定的插槽来授予父组件访问子组件数据的权限。
我们需要两个步骤来实现:
- 使用
v-bind让slot内容可以使用info - 在父级作用域中使用
v-slot访问slot属性 
首先,为了使子组件数据对父对象可用,我们可以将子组件的对象绑定为插槽上的一个属性。这些有界属性称为slot props。
// 子组件
<template>
  <div class="hello">
    <slot :data="data"> </slot>
  </div>
</template>
<script>
export default {
  data() {
    return {
      data: {
        list: ["zhangsan", "lisi", "wanwu", "zhaoliu", "tianqi", "xiaoba"],
        age: [18, 20, 22, 33, 16]
      }
    }
  }
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
然后,在我们的父组件中,我们可以使用<template>和v-slot指令来访问所有的 slot props。
// 父组件
<template>
  <div class="home">
    <child-component>
      <template v-slot:default="slotProps"> // 这边名字可以随意定义
          {{ slotProps.data.list }}
	  </template>
    </child-component>
  </div>
</template>
 1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 独占默认插槽的缩写语法
当被提供的内容只有默认插槽时,我们可以直接使用标签作为插槽的模板来使用。
// 父组件
<template>
  <div class="home">
    <child-component v-slot="slotProps">  // 也可以直接省略 :defualt
          <div>{{ slotProps.data.list }}</div>
    </child-component>
  </div>
</template>
 1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
如果存在多个插槽,最好给所有插槽使用完整的<template>的语法:
// 子组件
<template>
  <div class="hello">
    <slot :usrName="name"> </slot>
    <slot name="age" :age="age"> </slot>
  </div>
</template>
<script>
export default {
  data() {
    return {
        name: '李明',
        age: 18
    }
  }
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 父组件
<template>
  <div class="home">
    <child-component>
      <template v-slot:default="slotProps">{{ slotProps.usrName }}</template>
      <template v-slot:age="slotProps">{{ slotProps.age }}</template>
    </child-component>
  </div>
</template>
 1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 解构插槽Prop
当插槽提供了多个prop时,我们可以通过解构赋值的方式,选择一个或多个prop展示,同时也可以给该prop重命名。
看下面一个例子,子组件提供了两个属性,我们通过解构的方式拿到这两个属性,并进行了重命名:
// 子组件中
<slot :age="age" :weight="weight"> </slot>
// 父组件中
<child-component>
    <template v-slot:default="{ age: usrAge, weight: usrWeight }">
		{{ usrAge }}{{ usrWeight }}
    </template>
</child-component>
 1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
具名插槽也是一样的方法。
# 具名插槽的缩写
v-slot:header可以缩写为#header,具体如下:
<child-component>
  <template #header="{something...}">
    something...
  </template>
</child-component>
 1
2
3
4
5
2
3
4
5
缩写只能在其有插槽名时可用,如果是默认插槽可以这样:
<child-component>
  <template #default="{user}"> // 必须要有明确的插槽名
    something...
  </template>
</child-component>
 1
2
3
4
5
2
3
4
5
在GitHub上编辑  (opens new window)
  上次更新: 2/23/2022, 5:36:03 PM