[Vue3] defineAsyncComponent + component 动态引入组件、动态渲染组件

769 阅读1分钟

场景

用户访问:/index/about或者/index/contact,需要根据不同的参数去展示不同的组件

路由设置

非必要这样设置路由,根据实际情况来

export const constantRoutes = [
    {  
        // 如果有需要,这里也可以带多个参数,比如:/index/:value1/:value2
        path: '/index/:value',  
        name: 'index',  
        component: () => import("@/views/index.vue")  
    }  
]

代码思路

<script setup lang="ts">
import {defineAsyncComponent, isRef, shallowRef, unref, watch} from 'vue'
import {useRoute} from "vue-router";

// 为什么使用 shallowRef 可以百度一下
const elementRef = shallowRef(null);

const route = useRoute()

watch(() => route.params, (nVal, oVal) => {
  elementRef.value = defineAsyncComponent(() =>
      // 这里的 .value 对应 路由的 path: /index/:value
      import(`@/components/${nVal.value}.vue`)
  )
  // 需要加 immediate 初始化就运行监听
}, {immediate: true})

</script>

<template>
  <div>
    首页
    <component :is="elementRef"></component>
  </div>
</template>