哪里网站建设联系方式,直播软件哪个好用,网站建设公司antnw,php网站开发薪资 深圳shallowRef 用于创建一个浅层响应式引用#xff0c;只对顶层属性进行响应式处理。 markRaw 用于标记一个对象#xff0c;使其完全跳过 Vue 的响应式系统。
这两者都可以用于优化性能#xff0c;避免不必要的响应式开销#xff0c;特别是在处理大型对象或第三方库对象时。 …shallowRef 用于创建一个浅层响应式引用只对顶层属性进行响应式处理。 markRaw 用于标记一个对象使其完全跳过 Vue 的响应式系统。
这两者都可以用于优化性能避免不必要的响应式开销特别是在处理大型对象或第三方库对象时。
shallowRef
shallowRef 是 Vue 3 中的一个 API用于创建一个浅层响应式引用。与 ref 不同shallowRef 只会对其值的顶层进行响应式处理而不会递归地将其内部的对象变成响应式的。
用法
import { shallowRef } from vue;const state shallowRef({nested: {count: 0}
});// 只有 state 自身是响应式的state.nested 不是响应式的
state.value.nested.count; // 不会触发响应式更新适用场景
当你有一个复杂的对象但只需要对其顶层属性进行响应式处理时。当你需要避免对大型对象进行深层次的响应式处理以提高性能时。
markRaw
markRaw 是 Vue 3 中的一个 API用于标记一个对象使其永远不会被 Vue 的响应式系统处理。被标记为 markRaw 的对象将完全跳过响应式转换。
用法
import { markRaw } from vue;const rawObject markRaw({nested: {count: 0}
});// rawObject 及其所有嵌套属性都不是响应式的
rawObject.nested.count; // 不会触发响应式更新适用场景
当你有一个对象不需要响应式处理时。当你需要将第三方库的对象如 DOM 元素、图表实例等排除在响应式系统之外时。
下面的例子不能使用 ref ref 会将其值变成响应式对象而组件对象不应该是响应式的。为了避免这个问题可以使用 shallowRef 或者 markRaw 来处理组件对象。
示例在 Vue 组件中使用 shallowRef 和 markRaw
使用 shallowRef
templatedivbutton clicktoggleComponentToggle Component/buttoncomponent :iscurrentComponent //div
/templatescript setup
import { shallowRef } from vue;
import ComponentA from ./components/ComponentA.vue;
import ComponentB from ./components/ComponentB.vue;const currentComponent shallowRef(ComponentA);const toggleComponent () {currentComponent.value currentComponent.value ComponentA ? ComponentB : ComponentA;
};
/script使用 markRaw
templatedivbutton clicktoggleComponentToggle Component/buttoncomponent :iscurrentComponent //div
/templatescript setup
import { ref, markRaw } from vue;
import ComponentA from ./components/ComponentA.vue;
import ComponentB from ./components/ComponentB.vue;const ComponentA_raw markRaw(ComponentA);
const ComponentB_raw markRaw(ComponentB);const currentComponent ref(ComponentA_raw);const toggleComponent () {currentComponent.value currentComponent.value ComponentA_raw ? ComponentB_raw : ComponentA_raw;
};
/script