欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

[插槽 1 - 基本用法和默认值

最编程 2024-07-14 13:14:57
...

关于slot插槽的内容比较多,我们一点一点来学习,为了更好的理解slot的作用,我们一边写一个实例,一边来学习。
现在我们要开发一个标题栏组件,在开发中,我们经常会自己做一个标题栏,用来显示页面标题



我们先来写titleBar这个组件的基本结构,现在它显示的标题是固定的,

<template>
  <div class="title-bar">
    <div class="page-title">
      页面标题
    </div>
  </div>
</template>

<script>
export default {}
</script>

<style scoped>
.title-bar {
  width: 100%;
  height: 64px;
  background-color: #ccc;
position: relative;
}
.page-title {
  position: absolute;
  width: 100%;
  line-height: 64px;
  left: 0;
  top: 0;
  text-align: center;
}
</style>

在App.vue中使用它

<template>
  <div>
    <title-bar></title-bar>
  </div>
</template>

<script>
// slot插槽
import titleBar from './components/titleBar'
export default {
  name: 'App',
  components: { titleBar },
  data() {
    return {}
  },
}
</script>

<style>
html,
body {
  margin: 0;
}
</style>

现在我们的标题栏组件显示出来了,但是它显示固定内容,显然是不行的,我们需要把显示的标题变为动态,小伙伴们肯定想到了可以用之前学过的porps,从父组件向子组件传递数据的方式实现,
这节课我们要用slot这种方式,
修改titleBar文件的内容,增加<slot></slot>标签

<template>
  <div class="title-bar">
    <div class="page-title">
      <slot></slot>
    </div>
  </div>
</template>

slot中文翻译为插槽,我们可以理解为<slot></slot>标签在这里是一个槽,占了一个位置,等待父组件的内容插入进来
那我们来修改一下父组件的内容

<title-bar>来自父页面的标题</title-bar>

我们看到父组件把内容插入进来的方式是在标签里写上内容,跟原生标签插入内容的方式是一样的

<div>div里面的内容</div>

我们看一下最后渲染出来的html的内容

<div class="title-bar">
  <div class="page-title">来自父页面的标题</div>
</div>

我们看到<title-bar></title-bar>标签里的内容放到里<slot></slot>标签所占的位置

使用slot比使用props更强大的特点有一点就是slot可以直接插入html,比如

    <title-bar>
      <span style="color: red">来自父组件的标题</span>
    </title-bar>

渲染html的结果

<div class="title-bar">
  <div class="page-title">
    <span style="color: red;">来自父组件的标题</span>
  </div>
</div>

我们看到span标签占据了原来slot的位置
显示效果:



这就是slot最基本的用法了,简单来说就是在子组件中留个位置,在父组件中,写在标签内部的内容就会传递过来,占上空位。

我们titleBar这个组件在不用页面使用的时候,只要在标签里面写上相应的页面名称就行了

<title-bar>首页</title-bar>
<title-bar>商品详情</title-bar>

slot显示默认值

在使用titleBar时,内容并没有给它传递内容

<title-bar></title-bar>

这时当然就不显示内容了



如果你需要在插槽没有插入内容时,显示默认值,那就需要把默认值写在slot标签里面,
我们来修改titleBar的内容

<template>
  <div class="title-bar">
    <div class="page-title">
      <slot>未命名页面</slot>
    </div>
  </div>
</template>

这样,就可以显示一个默认值了



这节课重点主要在于理解slot起到了一个占位作用,父组件调用时,把标签里面的内容放到slot的位置。

推荐阅读