8

Vue3组件reactive object警告的可能出处:router

 2 years ago
source link: https://segmentfault.com/a/1190000040914146
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Vue3组件reactive object警告的可能出处:router

在使用ant-design-vue开发时,每次进入页面都有报以下这个warning:

[Vue warn]: Vue received a Component which was made a reactive object. This can lead to unnecessary performance overhead, and should be avoided by marking the component with `markRaw` or using `shallowRef` instead of `ref`. 

大概意思就是有一个组件,被包装成了响应式的对象,会造成不必要的性能开销。这个警告指向于以下的文件:

/src/layouts/BasicLayout.vue

第一反应就是在这个layout里面找问题,但始终解决不了。这里其实是进入了一个误区,以上警告其实是告诉你,BasicLayout这个组件被包装成了reactive的对象,而不是问题出在这个组件内部。

跳出误区后就好定位问题了,寻找引用了BasicLayout这个组件的功能代码。
一个可能的出处,是在router里面。因为项目里使用了动态路由,筛选后的路由对象,会存储在store里面,其中就包含了BasicLayout这个组件。

// 动态路由
export const asyncRouterMap: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'index',
    meta: { title: '首页' },
    component: BasicLayout, // 这里引用了BasicLayout组件
    redirect: '/welcome',
    children: [
      {
        path: 'welcome',
        name: 'Welcome',
        meta: { title: '欢迎页', icon: 'icon-antdesign' },
        component: () => import('@/views/welcome.vue')
      },
      ...
    ]
  },
  {
    path: '/:catchAll(.*)',
    name: 'NotFound',
    redirect: '/404'
  }
]

根据官方提示,将直接引入BasicLayout修改为shallowRef(BasicLayout)即可。

import { shallowRef } from 'vue'
...
component: shallowRef(BasicLayout),
...

除了上文提到的第一层的BasicLayout,下面如果有类似空白RouterView一类的component引用,都要加上shallowRef。

最近在用vue3+vite+antdv+ts写后台项目,遇到这个问题后,掉进误区搜了好久都没能解决,希望对大家有帮助吧。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK