给VUE组件动态生成name

1,086 阅读1分钟

方式一

  1. 创建 createCustomComponent.jsx 文件
import { defineComponent } from 'vue';
/**
 * 将指定组件设置自定义名称
 *
 * @param {String} name 组件自定义名称
 * @param {AsyncComponent} component
 * @return {Component}
 */
export default function createCustomComponent(customName, asyncComponent) {
    return defineComponent({
        name: customName,
        components: {
            AsyncComponent: asyncComponent,
        },
        setup() {
            return () => {
                return <AsyncComponent />;
            };
        },
    });
}
  1. 注册路由
import { defineAsyncComponent } from 'vue';
import createCustomComponent from './createCustomComponent.jsx';
...
{
   path: path,
   name: name,
   // component: () => import('@/views/Home.vue'),
   component: createCustomComponent(name, defineAsyncComponent(() => import('@/views/Home.vue'))),
   props: true
}

使用defineAsyncComponent引入的Home.vue是公用页面,这样就给公用页面包了一层壳,加上了自定义的名字。

方式二

  1. 创建createCustomComponent组件
/**
 * 将指定组件设置自定义名称
 *
 * @param {String} name 组件自定义名称
 * @param {Component | Promise<Component>} component
 * @return {Component}
 */
export function createCustomComponent (name, component) {
  return {
    name,
    data () {
      return { component: null }
    },
    async created () {
      if (component instanceof Promise) {
        try {
          const module = await component
          this.component = module?.default
        } catch (error) {
          console.error(`can not resolve component ${name}, error:`, error)
        }

        return
      }
      this.component = component
    },
    render (h) {
      return this.component ? h(this.component) : null
    },
  }
}
  1. 注册
{
  path: '/home/dashboard',
  name: 'DashboardC',
  component: createCustomComponent('DashboardC', import('@/views/home/Dashboard')),
  meta: {
    title: '数据看板'
  },
}