Vue received a Component that was made a reactive object. This can lead to unnecessary performance
技术栈:
vue3, pinia, vite, js
背景:
项目有一个layout组件,作用仅是提供路由<touter-view></router-view>,代码如截图所示

在路由配置文件router.config.js直接引入该组件

终端提示警告warning message
Vue received a Component that 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`.
Component that was made reactive:

原因分析:
将一个Vue组件对象转换为响应式对象时,可能会导致不必要的性能开销。这是因为Vue会对响应式对象进行递归式的深度观察,在对象的每个属性上都会添加getter和setter,以便能够在响应式对象发生变化时自动更新视图。
但是,在某些情况下,将Vue组件对象转换为响应式对象是不必要的,因为组件本身是Vue的核心概念,已经具有响应式的功能,因此,如果你将一个Vue组件对象转换为响应式对象,将会出现重复观察相同的对象属性的情况,导致不必要的性能开销。
为了避免这种情况,Vue建议使用markRaw方法将组件对象标记为非响应式对象,或者使用shallowRef代替ref来创建一个浅响应式对象
使用markRaw方法将组件对象标记为非响应式对象。例如
import { markRaw } from 'vue'
const MyComponent = {
/* ... 组件的定义 ... */
}
const myComponent = markRaw(MyComponent)
使用shallowRef代替ref来创建一个浅响应式对象,例如
import { shallowRef } from 'vue'
const MyComponent = {
/* ... 组件的定义 ... */
}
const myComponentRef = shallowRef(MyComponent)
解决方案:
在我们的例子中,我们在引用BlankLayout组件的位置,使用markRaw方法来标记其为非响应式对象:

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)