你还在为不懂插槽而烦恼吗

一.一般常见的插槽分为三种,默认,具名,作用域插槽

首先介绍一下默认和具名插槽的使用

父:

<template>
  <div class="">
    <!-- 匿名 -->
    <tanchuang>默认插槽</tanchuang>
    <!-- 具名 -->
    <tanchuang v-slot:hasname>具名插槽</tanchuang>
  </div>
</template>

<script>
import tanchuang from "./components/tanchuang.vue";
export default {
  components: {
    tanchuang,
  },
  name: "",
  methods: {},
};
</script>

<style scoped></style>

子:

<template>
  <div class="">
    <!-- 匿名 -->
    <slot></slot>
    <!-- 具名 -->
    <slot name="hasname"></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  name: "",
  methods: {},
};
</script>

<style scoped></style>

解析:默认插槽: 在父组件里面写上自己要写的内容,  在子组件里面通过<slot></slot>这个标签来进行接收。

       具名插槽: 顾名思义,就是有名字的插槽,在父组件上通过 v-slot: 名字 ,在子组件上通过

<slot name='名字'></slot>来进行接收。

      现在我们重点来讲一下作用域插槽,传递数据的插槽, 用法: 在子组件通过:名字=‘传递过去的数据’,接收的方法有两种, 在父组件里面可以通过:slot-scope='一个名字'用法,当作变量来进行使用,通过{{一个名字}}就可以看到传递的数据,但是不推荐使用在 2.6.0 中,我们为具名插槽和作用域插槽引入了一个新的统一的语法 (即 v-slot 指令)。它取代了 slot 和 slot-scope 这两个目前已被废弃但未被移除且仍在文档中的特性。新语法的由来可查阅这份 RFC。所以建议使用v-slot='啥名字都可以最好是语义化的名字'。

 代码

父:

<template>
  <div class="">
    <!-- 匿名 -->
    <tanchuang>默认插槽</tanchuang>
    <!-- 具名 -->
    <tanchuang v-slot:hasname>具名插槽</tanchuang>
    <!-- 作用域插槽 -->
    <tanchuang v-slot="aa">{{ aa }}</tanchuang>
  </div>
</template>

<script>
import tanchuang from "./components/tanchuang.vue";
export default {
  components: {
    tanchuang,
  },
  name: "",
  methods: {},
};
</script>

<style scoped></style>

子:

<template>
  <div class="">
    <!-- 匿名 -->
    <slot></slot>
    <!-- 具名 -->
    <slot name="hasname"></slot>
    <!-- 作用域 -->
    <slot :data="arr"></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr: [10, 20, 30, 40, 50],
    };
  },
  name: "",
  methods: {},
};
</script>

<style scoped></style>

二.图示

 结果:

总结:

1. 作用类似于子向父的过程,从<slot></slot>标签上通过动态绑定属性传递,类似于子---------父

2.任意的名字和任意的名字1  可以任意的取名字,建议语义化

3.匿名和具名插槽类似于父-------------->子

 三.实例应用场景

在我们平常开发中用的较少,一般在第三方组件(Element-ui等)里面进行使用:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值