vue3动态组件的使用

4,618 阅读1分钟

vue3动态组件<component></component>的使用

vue优化性能

使用场景

有些场景会需要在两个组件间来回切换,比如 Tab 界面:

image.png

这样的切换也可以用二级路由来完成,不过这里选择使用了 tab 切换,但是 tab 切换有一个小问题:切换 tab 时路由不会变,也就是说单纯的使用 <keep-alive>tab 切换是不起作用的,此时今天的主角就登场了===> <component></component> 动态组件

使用

1. 导入组件

import CepingVue from "../components/home/ceping.vue";
import Guanzhu from "../components/home/guanzhu.vue";
import Meiti from "../components/home/meiti.vue";
import Shipin from "../components/home/shipin.vue";
import Tuijian from "../components/home/tuijian.vue";
import Xinche from "../components/home/xinche.vue";

用拼音命名显得我很不专业,唉,但是它确实很好认!

2. 定义组件数组

const tabs = [Guanzhu, Tuijian, CepingVue, Xinche, Meiti, Shipin]

提示:动态组件不需要响应式,组件数组中也不需要加引号!

3. 模板使用

<template>
  <!-- 顶部tab栏 -->
  <van-tabs v-model:active="active" animated>
    <van-tab title="关注" />
    <van-tab title="推荐" />
    <van-tab title="测评" />
    <van-tab title="新车" />
    <van-tab title="全媒体" />
    <van-tab title="小视频" />
  </van-tabs>

  <!-- 动态组件 -->
  <component :is="tabs[active]"></component>
</template>

解析

项目中用了 vant 组件库的 <van-tabs> 组件,当我点击某一项时,active因为双向数据绑定的原因会随之改变,所以 :is="tabs[active]" 也会随之切换到对应的组件,如果是自己写的或者用自己封装的tab组件,可根据实际情况做改变,反正就是通过下标去组件数组中拿到对应的组件来展示

你以为结束了?!

当使用 <component :is="..."> 来在多个组件间作切换时,被切换掉的组件会被卸载。

想让它不被卸载,那当然还是得用<keep-alive>来缓存组件啦

  <!-- 动态组件 -->
  <keep-alive>
    <component :is="tabs[active]"></component>
  </keep-alive>

<component>外层包一层<keep-alive>就完事了,好端端。这次就真的结束了!