Vue3动态组件去进行异常处理
动态组件有两种常用场景:
一是动态路由:
// 动态路由
export const asyncRouterMap: Array<RouteRecordRaw> = [
{
path: '/',
name: 'index',
meta: { title: '首页' },
component: BasicLayout, // 引用了 BasicLayout 组件
redirect: '/welcome',
children: [
{
path: 'welcome',
name: 'Welcome',
meta: { title: '引导页' },
component: () => import('@/views/welcome.vue')
},
...
]
}
]
二是动态渲染组件,比如在 Tabs 中切换:
<el-tabs :model-value="copyTabName" type="card">
<template v-for="item in tabList" :key="item.key || item.name">
<el-tab-pane
:name="item.key"
:label="item.name"
:disabled="item.disabled"
:lazy="item.lazy || true"
>
<template #label>
<span>
<component v-if="item.icon" :is="item.icon" />
{{ item.name }}
</span>
</template>
// 关键在这里
<component :key="item.key || item.name" :is="item.component" v-bind="item.props" />
</el-tab-pane>
</template>
</el-tabs>
在 vue2 中使用并不会引发什么其他的问题,但是当你将组件包装成一个响应式对象时,在 vue3 中,会出现一个警告:
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
.
出现这个警告是因为:使用 reactive 或 ref(在 data 函数中声明也是一样的)声明变量会做 proxy 代理,而我们组件代理之后并没有其他用处,为了节省性能开销,vue 推荐我们使用 shallowRef 或者 markRaw 跳过 proxy 代理。
解决方法如上所说,需要使用 shallowRef 或 markRaw 进行处理:
对于 Tabs 的处理:
import { markRaw, ref } from 'vue'
import A from './components/A.vue'
import B from './components/B.vue'
interface ComponentList {
name: string
component: Component
// ...
}
const tab = ref<ComponentList[]>([{
name: "组件 A",
component: markRaw(A)
}, {
name: "组件 B",
component: markRaw(B)
}])
对于动态路由的处理:
import { markRaw } from 'vue'
// 动态路由
export const asyncRouterMap: Array<RouteRecordRaw> = [
{
path: '/',
name: 'home',
meta: { title: '首页' },
component: markRaw(BasicLayout), // 使用 markRaw
// ...
}
]
而对于 shallowRef 和 markRaw,2 者的区别在于 shallowRef 只会对 value 的修改做出反应,比如:
const state = shallowRef({ count: 1 })
// 不会触发更改
state.value.count = 2
// 会触发更改
state.value = { count: 2 }
而 markRaw,是将一个对象标记为不可被转为代理。然后返回该对象本身。
const foo = markRaw({})
console.log(isReactive(reactive(foo))) // false
// 也适用于嵌套在其他响应性对象
const bar = reactive({ foo })
console.log(isReactive(bar.foo)) // false
可看到,被 markRaw 处理过的对象已经不是一个响应式对象了。
对于一个组件来说,它不应该是一个响应式对象,在处理时,shallowRef 和 markRaw 2 个 API,推荐使用 markRaw 进行处理。
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanfceie
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
excel下划线不显示怎么办
PHP中文网 06-23 -
怎样阻止微信小程序自动打开
PHP中文网 06-13 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
photoshop蒙版画笔没反应怎么办
PHP中文网 06-24