组件响应式如果用ref 会导致性能问题,会提示:

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`.

使用 markRaw 或 shallowRef替代,原因分析如下:

当您在 Vue 3 组件中使用一个对象作为组件时,Vue 的响应式系统会自动将这个对象转换为响应式对象。这可能会带来一些不必要的性能开销,因为 Vue 需要监听对象中每个属性的变化。

为了避免这个问题,Vue 建议您使用 markRaw 或 shallowRef 来标记这个组件对象,告诉 Vue 不需要对它进行响应式转换。

markRaw: 将一个对象标记为不应该转换为响应式对象。

shallowRef: 创建一个浅层的响应式引用,只有引用本身是响应式的,而不是它指向的值。

代码实例:

<component :is="component" :params="params"></component>



<script setup>

import { ref,watch, onMounted,markRaw, shallowRef } from 'vue'

const viteComponents = import.meta.glob('./*.vue') //动态加载布局

let activeIndex = ref('videoRealTime')///默认选中

const component = shallowRef(null);

//切换布局的函数

const handleSelect = (key, keyPath) => {

console.log('handleSelect', key, keyPath)

activeIndex.value = key

getComponent()

}

const params = ref({'key':'yes'}) //页面参数

const getComponent = async ()=>{

let module = await viteComponents['./'+activeIndex.value+'.vue']();

component.value = module.default || module;

}

onMounted(()=>{

getComponent()

})

</script>

OK,就这么简单。。。。。。