目录
插槽(slot)是用来 在子组件挂载时 向子组件内部注入自定义内容的工具
插槽的用法
1.匿名插槽
2.具名插槽
3.带有作用域的插槽
所有插槽的用法 都分为两步
1.在子组件中挖坑
2.在父组件中插值
匿名插槽用法
1.子组件挖坑
在子组件模板中想要进行插入自定义html内容的位置 写入 slot标签
- <div>
- <h1>{{content}}h1>
-
- <slot>slot>
- div>
-
- export default {
- data() {
- return {
- content:"我是子组件"
- };
- },
- };
-
2.父组件插值
在指定的子组件标签中 写入自己想要插入的html内容即可
- <div>
- <h1>{{content}}h1>
- <v-child>
-
- <div>123div>
- <div>456div>
- ...
- v-child>
- <v-child1>v-child1>
- <v-child2>v-child2>
- div>
-
- import VChild from "./VChild.vue"
- import VChild1 from "./VChild1.vue"
- import VChild2 from "./VChild2.vue"
- export default {
- data() {
- return {
- content:"我是父组件"
- };
- },
- components:{
- VChild,
- VChild1,
- VChild2,
- }
- };
-
1.子组件挖坑
在子组件中 想插值的位置 写入slot标签 但是 slot标签 需要设置name属性
- <div>
- <h1>{{content}}h1>
-
- <slot name="child1">slot>
- div>
-
- export default {
- data() {
- return {
- content:"我是子组件"
- };
- },
- };
-
2.父组件插值
在设置了slot插槽的子组件标签内部 写入我们想要插入的html内容 但是 插入的html内容的根元素 要设置属性slot 值为之前子组件中slot的name值
- <div>
- <h1>{{content}}h1>
- <v-child>
-
- <div>123div>
- <div>456div>
- ...
- v-child>
- <v-child1>
- <ul slot="child1">
- <li>xxxli>
- <li>xxxli>
- ...
- ul>
- v-child1>
- <v-child2>v-child2>
- div>
-
- import VChild from "./VChild.vue"
- import VChild1 from "./VChild1.vue"
- import VChild2 from "./VChild2.vue"
- export default {
- data() {
- return {
- content:"我是父组件"
- };
- },
- components:{
- VChild,
- VChild1,
- VChild2,
- }
- };
-
不仅可以插值 而且可以在插入的自定义html内容中 使用子组件提供的数据进行渲染
1.挖坑
子组件中 想插值的位置 写入slot标签 但是slot标签需要设置一个自定义属性,属性值为要传递的数据
- <div>
- <h1>{{content}}h1>
-
- <slot :自定义属性名="数据">slot>
- div>
-
- export default {
- data() {
- return {
- 属性名:slot要使用的数据,
- content:"我是子组件"
- };
- },
- };
-
2.插值
父组件中 需要在子组件标签中 写入template标签 并在template标签中 写入要插入的html内容
之后还要给template设置属性——v-slot 属性值固定 为 scope
- <div>
- <h1>{{content}}h1>
- <v-child>
-
- <div>123div>
- <div>456div>
- ...
- v-child>
- <v-child1>
- <ul slot="child1">
- <li>xxxli>
- <li>xxxli>
- ...
- ul>
- v-child1>
- <v-child2>
-
-
- <template v-slot="scope">
- xxxx
- template>
- v-child2>
- div>
-
- import VChild from "./VChild.vue"
- import VChild1 from "./VChild1.vue"
- import VChild2 from "./VChild2.vue"
- export default {
- data() {
- return {
- content:"我是父组件"
- };
- },
- components:{
- VChild,
- VChild1,
- VChild2,
- }
- };
-