<template> <h1>{ { counter1 }}</h1> <hr> <h1>{ { data.x }}</h1> <button @click="counter1++">加加</button> <hr> <button @click="data.x.counter2++">新属性加加</button> <hr> <button @click="getRawObject">获取原始对象</button> <hr> <button @click="add">拓展属性</button> </template> <script> import { markRaw, reactive, toRaw, toRefs } from 'vue' export default { name : "App", setup(){ let data = reactive({ // 这里的原始对象的值也被修改了 counter1 : 1 }); // 获取响应式对象的原始对象 // 操作这个对象没有响应式处理 function getRawObject(){ let rawObj = toRaw(data); rawObj.counter1++; // 原始对象也关联我们初始的这个对象的,修改的时候也被修改了 console.log(rawObj); // 修改原始对象没有响应式 } function add(){ // 是响应式的,因为我们底层添加也是调用的set方法 // 以Proxy代理对象的形式执行了set方法 // 因此是具有响应式的 // 标记为markRaw后这个属性就是原始对象了,不具有响应式 // 底层也没有创建Proxy对象,极大的提升了效率 data.x = markRaw({ counter2 : 100 }); } return { data, getRawObject, add, ...toRefs(data) }; } } </script> <style> </style>
<template>
<h1>{ { counter1 }}</h1>
<hr>
<h1>{ { data.x }}</h1>
<button @click="counter1++">加加</button>
<hr>
<button @click="data.x.counter2++">New attribute plus</button>
<hr>
<button @click="getRawObject">Get the original object</button>
<hr>
<button @click="add">Extended attributes</button>
</template>
<script>
import { markRaw, reactive, toRaw, toRefs } from 'vue'
export default {
name : "App",
setup(){
let data = reactive({
//The value of the original object here is also modified
counter1 : 1
});
// Get the original object of the responsive object
// There is no reactive processing when operating this object
function getRawObject(){
let rawObj = toRaw(data);
rawObj.counter1++;
// The original object is also associated with our initial object, and is also modified when modified.
console.log(rawObj);
// Modifying the original object is not responsive
}
function add(){
// It is responsive, because we also call the set method when adding it at the bottom
//The set method is executed in the form of Proxy object
// Therefore it is responsive
// After marking it as markRaw, this attribute becomes the original object and is not responsive.
// There is no Proxy object created at the bottom layer, which greatly improves efficiency.
data.x = markRaw({
counter2 : 100
});
}
return {
data,
getRawObject,
add,
...toRefs(data)
};
}
}
</script>
<style>
</style>
VUE framework Vue3 uses toRaw and markRaw to mark and convert to raw to optimize project efficiency------VUE framework
Guess you like
Origin blog.csdn.net/2201_75960169/article/details/135270674
Recommended
Ranking