三分钟带你弄懂slot插槽——vue进阶

三分钟带你弄懂slot插槽——vue进阶

一、概述

当然,你可以先看完例子之后再回来看概述或者官方文档

程序员之死

在项目的开发中,代码冗余一直是程序员头疼的事情

小白程序员必会遇到的情况之一,就是写一个大项目,然后无限的 ctrl+c 和 ctrl-v,到差不多项目DDL了,甲方告诉你要改这个地方,要改那个地方,然后你就又一波 ctrl+c 和 ctrl-v

当你搞完这30几次的 ctrl+c 和 ctrl-v后,啊……这……什么鬼,报错了

当你改完bug之后,甲方:“改回去吧,我不要了”

这时,怎一个艹字头了的,当场升天的心都有了

这个时候,组件就显得尤为重要

使用好 “slot插槽” 能够让你再使用组件的时候更游刃有余

什么是 slot插槽?

我是这么理解的:

slot定义在子组件中,slot中的内容权重为1
在父组件中,权重为10

也就是说:如果父组件中没有内容去“替换”子组件的slot,那么默认渲染出子组件中的内容

<!--子组件 mytemplate 中-->
<template>
	<slot>header</slot>
</template>

<!--父组件1中-->
<mytemplate></mytemplate>

<!--父组件2中-->
<mytemplate>
	change header
</mytemplate>

这样,父组件1中显示为 header,父组件2中显示为 change header

2.6.0 版本中的 slot

在 2.6.0 中,我们为具名插槽和作用域插槽引入了一个新的统一的语法 (即 v-slot 指令)。
它取代了 slot 和 slot-scope 这两个目前已被废弃但未被移除且仍在文档中的 attribute。

二、具名插槽

在2.6.0中,已经使用 name 和 v-slot 进行搭配了,不填name默认为 name = “default”

例子

下面我用一个例子来帮助大家理解 slot插槽

效果图

在这里插入图片描述

帮大家捋一下思路:

子组件由title、img、content三部分组成,我们要做的效果就是左边放默认的子组件效果,右边的替换掉插槽,用上我们在父组件中定义内容

子组件定义三个具名插槽(要是不定义name的话,全部默认为defult就会出事了)然后再父组件中,用 v-slot:[名字] 来替换默认插槽

代码

Slot-Component.vue

<!--这是作图的默认效果,在子组件中-->
<template>
  <div class="container">
    <strong>
      <slot name="slot-title">title</slot>
    </strong>
    <slot name="slot-img">
      <img src="http://localhost:9999/img/1.png" alt />
    </slot>
    <p style="color:#666">
      <slot name="slot-content">content</slot>
    </p>
  </div>
</template>

<style scoped>
* {
  padding: 0;
  background: 0;
  margin: 0;
}
.container {
  width: 200px;
  height: 200px;
  overflow: hidden;
  background: #f0f0f0;
  border: 0.5rem solid #999;
  margin: 1rem;
}
.container strong {
  display: block;
  height: 2rem;
  line-height: 2rem;
}
.container p {
  height: 2rem;
  line-height: 2rem;
}
.container img {
  height: calc(100% - 4rem);
}
</style>

Father.vue

<template>
  <div class="container">
    <slotComponent class="margin-auto"></slotComponent>
    <slotComponent class="margin-auto">
      <template v-slot:slot-title>mytitle</template>
      <template v-slot:slot-img>
        <img src="http://localhost:9999/img/2.png" alt />
      </template>
      <template v-slot:slot-content>mycontent</template>
    </slotComponent>
  </div>
</template>

<script>
import slotComponent from "../components/Slot-Component";
export default {
  components: { slotComponent }
};
</script>

<style scoped>
.margin-auto {
  display: inline-block;
}
</style>

三、小惊喜

slot插槽中,< slot >标签是定义不了样式了,行内样式也不行!为什么呢?请按F12查看一下是否还有< slot >标签的存在。

猜你喜欢

转载自blog.csdn.net/qq_41297145/article/details/106649499
今日推荐