vue3的reactive
2022-07-01 本文已影响0人
Birdd
reactive
用来绑定复杂的数据类型 例如 对象 数组
reactive 源码约束了我们的类型,不可以绑定普通的数据类型
如果用ref去绑定对象 或者 数组 等复杂的数据类型 我们看源码里面其实也是 去调用reactive
★使用reactive 去修改值无须.value
异步数组无法响应改变
解决1:push
解决2:包一层对象
//改变Reactive
const valueReactive = reactive({
name: "乌瑟尔",
});
function changeReactive() {
valueReactive.name = "卡德加";
}
function changeReactiveAll() {
valueReactive = {name:"吉安娜"};
console.log(valueReactive.name)
}
readonly
拷贝一份proxy对象将其设置为只读,改变会报错
shallowReactive
只能对浅层的数据 如果是深层的数据只会改变值 不会改变视图
当你改变第一层数据时,如果是在改变第一层的时候改变其他值,其他值也会响应,
如果直接改变深层,无法响应
<template>
Reactive{{ valueReactive.name }}
<button @click="changeReactive()">改变Reactive</button>
<button @click="changeReactiveAll()">改变ReactiveALL</button>
<button @click="changeReactiveAsync()">异步改变Reactive</button>
readonly{{ readonlyValue }}
<button @click="changeReadOnly()">改变readOnly</button>
<div>
ReactiveValue:{{ shallowReactiveValue }}
<button @click="changeshallowReactive1()">改变ReactiveValue1</button>
<button @click="changeshallowReactive2()">改变ReactiveValue2</button>
<button @click="changeshallowReactive3()">改变ReactiveValue3</button>
<button @click="changeshallowReactive4()">改变ReactiveValue4</button>
</div>
</template>
<script>
import {
ref,
shallowReactive,
shallowRef,
triggerRef,
customRef,
reactive,
readonly,
} from "vue";
export default {
setup() {
//改变Reactive
let valueReactive = reactive({
name: "乌瑟尔",
});
function changeReactive() {
valueReactive.name = "卡德加";
}
function changeReactiveAll() {
valueReactive = { name: "吉安娜" };
console.log(valueReactive.name);
}
function changeReactiveAsync() {
setTimeout(() => {
valueReactive.name = "奈法利安";
console.log(valueReactive.name);
}, 1000);
}
let readonlyValue = readonly(valueReactive);
function changeReadOnly() {
readonlyValue.name = "卡德加";
}
let shallowReactiveValue = shallowReactive({
name: "爷爷",
child: {
name: "爸爸",
child: {
name: "孙子",
},
},
});
function changeshallowReactive1() {
shallowReactiveValue.name = "卡德加爷爷";
shallowReactiveValue.child.name = "卡德加爸爸";
shallowReactiveValue.child.child.name = "卡德加孙子";
console.log(shallowReactiveValue);
}
function changeshallowReactive2() {
shallowReactiveValue.child.name = "赵刚爸爸";
console.log(shallowReactiveValue);
}
function changeshallowReactive3() {
shallowReactiveValue.child.child.name = "李云龙孙子";
console.log(shallowReactiveValue);
}
function changeshallowReactive4() {
shallowReactiveValue.name = "易学习爷爷";
console.log(shallowReactiveValue);
}
return {
valueReactive,
changeReactive,
changeReactiveAll,
changeReactiveAsync,
readonlyValue,
changeReadOnly,
shallowReactiveValue,
changeshallowReactive1,
changeshallowReactive2,
changeshallowReactive3,
changeshallowReactive4,
};
},
};
</script>