Vue组件化-插槽Slot和非父子通信

一、认识插槽Slot作用

1.认识插槽Slot

在开发中,我们会经常封装一个个可复用的组件:

  • 前面我们会通过props传递给组件一些数据,让组件来进行展示;
  • 但是为了让这个组件具备更强的通用性,我们不能将组件中的内容限制为固定的div、span等等这些元素;
  • 比如某种情况下我们使用组件,希望组件显示的是一个按钮,某种情况下我们使用组件希望显示的是一张图片;
  • 我们应该让使用者可以决定某一块区域到底存放什么内容和元素;

举个栗子:假如我们定制一个通用的导航组件 - NavBar

  • 这个组件分成三块区域:左边-中间-右边,每块区域的内容是不固定;
  • 左边区域可能显示一个菜单图标,也可能显示一个返回按钮,可能什么都不显示;
  • 中间区域可能显示一个搜索框,也可能是一个列表,也可能是一个标题,等等;
  • 右边可能是一个文字,也可能是一个图标,也可能什么都不显示;

在这里插入图片描述

二、插槽Slot基本使用

1.如何使用插槽slot?

这个时候我们就可以来定义插槽slot:

  • 插槽的使用过程其实是抽取共性预留不同
  • 我们会将共同的元素、内容依然在组件内进行封装;
  • 同时会将不同的元素使用slot作为占位,让外部决定到底显示什么样的元素;

如何使用slot呢?

  • Vue中将元素作为承载分发内容的出口;

  • 在封装组件中,使用特殊的元素就可以为封装组件开启一个插槽;

  • 该插槽插入什么内容取决于父组件如何使用;

在这里插入图片描述

2.插槽的默认内容

有时候我们希望在使用插槽时,如果没有插入对应的内容,那么我们需要显示一个默认的内容:

  • 当然这个默认的内容只会在没有提供插入的内容时,才会显示;
<template>
  <h2>{{ title }}</h2>
  <div class="content">
    <slot>
      <p>我是默认内容, 哈哈哈</p>
    </slot>
  </div>
</template>

3.多个插槽的效果

我们先测试一个知识点:如果一个组件中含有多个插槽,我们插入多个内容时是什么效果?

  • 我们会发现默认情况下每个插槽都会获取到我们插入的内容来显示

在这里插入图片描述

4.插槽的基本使用

我们一个组件MySlotCpn.vue:该组件中有一个插槽,我们可以在插槽中放入需要显示的内容;

我们在App.vue中使用它们:

  • 我们可以插入普通的内容、html元素、组件,都可以是可以的;
<template>
  <div class="app">
    <!-- 1.内容是button -->
    <show-message title="哈哈哈">
      <button>我是按钮元素</button>
    </show-message>

    <!-- 2.内容是超链接 -->
    <show-message>
      <a href="#">百度一下</a>
    </show-message>

    <!-- 3.内容是一张图片 -->
    <show-message>
      <img src="@/img/kobe02.png" alt="">
    </show-message>

    <!-- 4.内容没有传递 -->
    <show-message></show-message>
  </div>
</template>

<script>
  import ShowMessage from './ShowMessage.vue'

  export default {
    components: {
      ShowMessage
    }
  }
</script>

<style scoped>
</style>

三、具名插槽Slot使用

事实上,我们希望达到的效果是插槽对应的显示,这个时候我们就可以使用具名插槽

  • 具名插槽顾名思义就是给插槽起一个名字, 元素有一个特殊的 attribute:name;
  • 一个不带 name 的slot,会带有隐含的名字 default

App.vue

<template>
  <nav-bar>
    <template #left>
      <button>{{ leftText }}</button>
    </template>

    <template #center>
      <span>内容</span>
    </template>

    <template v-slot:right>
      <a href="#">登录</a>
    </template>
  </nav-bar>

  <!-- nav-bar只给一个插槽传入数据 -->
  <nav-bar>
    <template v-slot:[position]>
      <a href="#">注册</a>
    </template>
  </nav-bar>
  <button @click=" position = 'left' ">左边</button>
  <button @click=" position = 'center' ">中间</button>
  <button @click=" position = 'right' ">右边</button>
</template>

<script>
  import NavBar from './NavBar.vue'

  export default {
    components: {
      NavBar
    },
    data() {
      return {
        position: "center",
        leftText: "返回"
      }
    }
  }
</script>

<style scoped>
</style>

NavBar.vue

<template>
  <div class="nav-bar">
    <div class="left">
      <slot name="left">left</slot>
    </div>
    <div class="center">
      <slot name="center">center</slot>
    </div>
    <div class="right">
      <slot name="right">right</slot>
    </div>
  </div>

  <div class="other">
    <slot name="default"></slot>
  </div>
</template>

<script>
  export default {

  }
</script>

<style scoped>
  .nav-bar {
    display: flex;
    height: 44px;
    line-height: 44px;
    text-align: center;
  }

  .left {
    width: 80px;
    background-color: orange;
  }

  .center {
    flex: 1;
    background-color: skyblue;
  }

  .right {
    width: 80px;
    background-color: aquamarine;
  }
</style>

1.具名插槽缩写

具名插槽使用的时候缩写:

  • 跟 v-on 和 v-bind 一样,v-slot 也有缩写;
  • 即把参数之前的所有内容 (v-slot:) 替换为字符 #
<template>
    <nav-bar>
        <template #left>
            <button>{{ leftText }}</button>
        </template>

        <template #center>
            <span>内容</span>
        </template>

        <template v-slot:right>
            <a href="#">登录</a>
        </template>
    </nav-bar>

2.动态插槽名

什么是动态插槽名呢?

  • 目前我们使用的插槽名称都是固定的;
  • 比如 v-slot:left、v-slot:center等等;
  • 我们可以通过 v-slot:[dynamicSlotName]方式动态绑定一个名称;
<template>
  <my-slot>
    <template #[slotName]>
      我是随机的内容
    </template>
  </my-slot>
</template>
<script>
import MySlot from './MySlot.vue';

export default {
  data() {
    return {
      slotName: 'center'
    }
  },
  components: {
    MySlot
  }
}
</script>

四、作用域插槽Slot使用

1.渲染作用域

在Vue中有渲染作用域的概念:

  • 父级模板里的所有内容都是在父级作用域中编译的;
  • 子模板里的所有内容都是在子作用域中编译的;

如何理解这句话呢?我们来看一个案例:

  • 在我们的案例中ChildCpn自然是可以让问自己作用域中的title内容的;
  • 但是在App中,是访问不了ChildCpn中的内容的,因为它们是跨作用域的访问;

在这里插入图片描述

2.认识作用域插槽

但是有时候我们希望插槽可以访问到子组件中的内容是非常重要的:

  • 当一个组件被用来渲染一个数组元素时,我们使用插槽,并且希望插槽中没有显示每项的内容;
  • 这个Vue给我们提供了作用域插槽

我们来看下面的一个案例:

  1. 在App.vue中定义好数据
  2. 传递给ShowNames组件中
  3. ShowNames组件中遍历names数据
  4. 定义插槽的prop
  5. 通过v-slot:default的方式获取到slot的props
  6. 使用slotProps中的item和index

在这里插入图片描述

3.独占默认插槽的缩写

如果我们的插槽是默认插槽default,那么在使用的时候 v-slot:default="slotProps"可以简写为v-slot=“slotProps”:

<!-- 3.独占默认插槽的简写(了解) -->
<tab-control :titles="['衣服', '鞋子', '裤子']" 
             @tab-item-click="tabItemClick">
    <template v-slot="props">
        <button>{{ props.item }}</button>
    </template>
</tab-control>

并且如果我们的插槽只有默认插槽时,组件的标签可以被当做插槽的模板来使用,这样,我们就可以将 v-slot 直接用在组件上:

<!-- 4.如果只有一个默认插槽, 那么template可以省略 -->
<tab-control :titles="['衣服', '鞋子', '裤子']" 
             @tab-item-click="tabItemClick"
             v-slot="props">
    <button>{{ props.item }}</button>
</tab-control>

4.默认插槽和具名插槽混合

但是,如果我们有默认插槽和具名插槽,那么按照完整的template来编写。

在这里插入图片描述

只要出现多个插槽,请始终为所有的插槽使用完整的基于 <template>的语法

在这里插入图片描述

<template>
  <div class="app">
    <!-- 1.tab-control -->
    <tab-control :titles="['衣服', '鞋子', '裤子']" 
                 @tab-item-click="tabItemClick"/>

    <!-- <tab-control :titles="['流行', '最新', '优选']"/> -->

    <!-- 2.展示内容 -->
    <h1>{{ pageContents[currentIndex] }}</h1>

    <!-- 1.tab-control: button -->
    <tab-control :titles="['衣服', '鞋子', '裤子']" 
                 @tab-item-click="tabItemClick">
      <template v-slot:default="props">
        <button>{{ props.item }}</button>
      </template>
    </tab-control>

    
    <!-- 2.tab-control: a元素(重要) -->
    <tab-control :titles="['衣服', '鞋子', '裤子']" 
                 @tab-item-click="tabItemClick">
      <template #default="props">
        <a href="#">{{ props.item }}</a>
      </template>
    </tab-control>

    <!-- 3.独占默认插槽的简写(了解) -->
    <tab-control :titles="['衣服', '鞋子', '裤子']" 
                 @tab-item-click="tabItemClick">
      <template v-slot="props">
        <button>{{ props.item }}</button>
      </template>
    </tab-control>

    <!-- 4.如果只有一个默认插槽, 那么template可以省略 -->
    <tab-control :titles="['衣服', '鞋子', '裤子']" 
                 @tab-item-click="tabItemClick"
                 v-slot="props">
      <button>{{ props.item }}</button>
    </tab-control>
  </div>
</template>

<script>
  import TabControl from './TabControl.vue'

  export default {
    components: {
      TabControl
    },
    data() {
      return {
        pageContents: [ "衣服列表", "鞋子列表", "裤子列表" ],
        currentIndex: 0
      }
    },
    methods: {
      tabItemClick(index) {
        console.log("app:", index)
        this.currentIndex = index
      }
    }
  }
</script>

<style scoped>
</style>

TabControl.vue

<template>
  <div class="tab-control">
    <template v-for="(item, index) in titles" :key="item">
      <div class="tab-control-item"
           :class="{ active: index === currentIndex }"
           @click="itemClick(index)">
        <slot :item="item" abc="cba">
          <span>{{ item }}</span>
        </slot>
      </div>
    </template>
  </div>
</template>

<script>
  export default {
    props: {
      titles: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        currentIndex: 0
      }
    },
    emits: ["tabItemClick"],
    methods: {
      itemClick(index) {
        this.currentIndex = index
        this.$emit("tabItemClick", index)
      }
    }
  }
</script>

<style scoped>
  .tab-control {
    display: flex;
    height: 44px;
    line-height: 44px;
    text-align: center;
  }

  .tab-control-item {
    flex: 1;
  }

  .tab-control-item.active {
    color: red;
    font-weight: 700;
  }

  .tab-control-item.active span {
    border-bottom: 3px solid red;
    padding: 8px;
  }
</style>

五、全局事件总线使用

1.非父子组件的通信

在开发中,我们构建了组件树之后,除了父子组件之间的通信之外,还会有非父子组件之间的通信。

这里我们主要讲两种方式:

  • 全局事件总线
  • Provide/Inject

2.全局事件总线mitt库

Vue3从实例中移除了 $on$off$once 方法,所以我们如果希望继续使用全局事件总线,要通过第三方的库:

  • Vue3官方有推荐一些库,例如 mitttiny-emitter
  • 这里我们主要讲解一下 mitt 的使用;

首先,我们需要先安装这个库:

npm install mitt --save

其次,我们可以封装一个工具eventbus.js:

import mitt from 'mitt'

const emitter = mitt()

export default emitter

3.使用事件总线工具

在项目中可以使用它们:

  • 我们在App.vue中触发事件;
  • 我们在Banner.vue中监听事件;

App.vue

<script>
import emitter from './utils/eventbus';

export default {
    methods: {
        add() {
            // 发送事件
            emitter.emit('foo', { a: 'b'} )
        }
    }
}
    
</script>

Banner.vue

<script>
import emitter from './utils/eventbus';

export default {
    methods: {
        add() {
            // 监听事件
            emitter.on('foo', e => console.log('foo', e) )
        }
    }
}
    
</script>

Mitt的事件取消

在某些情况下我们可能希望取消掉之前注册的函数监听:

function onFoo() {}
emitter.on('foo', onFoo)   // listen
emitter.off('foo', onFoo)  // unlisten

六、依赖注入Provide/Inject

1.Provide和Inject

Provide/Inject用于非父子组件之间共享数据:

  • 比如有一些深度嵌套的组件,子组件想要获取父组件的部分内容;
  • 在这种情况下,如果我们仍然将props沿着组件链逐级传递下去,就会非常的麻烦;

对于这种情况下,我们可以使用 Provide 和 Inject :

  • 无论层级结构有多深,父组件都可以作为其所有子组件的依赖提供者;
  • 父组件有一个 provide 选项来提供数据;
  • 子组件有一个 inject 选项来开始使用这些数据;

实际上,你可以将依赖注入看作是“long range props”,除了:

  • 父组件不需要知道哪些子组件使用它 provide 的 property
  • 子组件不需要知道 inject 的 property 来自哪里

在这里插入图片描述

2.Provide和Inject基本使用

我们开发一个这样的结构:

在这里插入图片描述

在这里插入图片描述

3.Provide和Inject函数的写法

如果Provide中提供的一些数据是来自data,那么我们可能会想要通过this来获取:

这个时候会报错:

  • 这里给大家留一个思考题,我们的this使用的是哪里的this?(答案:window)

在这里插入图片描述

4.处理响应式数据

我们先来验证一个结果:如果我们修改了this.names的内容,那么使用length的子组件会不会是响应式的?

我们会发现对应的子组件中是没有反应的:

  • 这是因为当我们修改了names之后,之前在provide中引入的 this.names.length 本身并不是响应式的;

那么怎么样可以让我们的数据变成响应式的呢?

  • 非常的简单,我们可以使用响应式的一些API来完成这些功能,比如说computed函数;
  • 当然,这个computed是vue3的新特性,在后面我会专门讲解,这里大家可以先直接使用一下;

注意:我们在使用length的时候需要获取其中的value

  • 这是因为computed返回的是一个ref对象,需要取出其中的value来使用;

在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值