第7章 认识Reactive全家桶
用来绑定复杂的数据类型 例如 对象 数组
简单的数据类型用ref.
一、reactive
改值:
let message_reactive=reactive([]);
let obj=reactive({id:"搜索"});
obj.id="撒啊";
<div>arr{{message_reactive}}</div>
<div>object{{obj}}</div>
数组赋值:第一种 push的方式
let message_reactive_push=reactive<number[]> ([])
setTimeout(() => {
let arr3=[1,2,3,4];
**message_reactive_push.push(...arr3);**
console.log(message_reactive_push);
}, 1000);
<div>数组赋值arr{{message_reactive_push}}</div>
数组赋值:第二种 type的方式
type O={
list:number[]
}
let message_reactive_type=reactive<O> ({
list:[null]
})
setTimeout(() => {
message_reactive_type.list=[1,2,3,4,9];
console.log(message_reactive_type);
}, 1000);
<div>数组赋值arr{{message_reactive_type.list}}</div>
二、readonly只读;
拷贝一份proxy对象将其设置为只读
import { reactive ,readonly} from 'vue'
const person = reactive({count:1})
const copy = readonly(person)
//person.count++
copy.count++ 报错
三、shallowReactive ;
只能对浅层的数据 如果是深层的数据只会改变值 不会改变视图。
响应浅层值,不响应深层值;
最终确认值都会被改,只是深层值不会在界面上显示;
let message_shallow_reactive=shallowReactive({
test:"第一层",
nav:{
foo:{
bar:"第三层"
}
}
})
function change1(){
message_shallow_reactive.test="我被改了"
}
function change2(){
message_shallow_reactive.nav.foo.bar="我被改了2"
console.log(message_shallow_reactive);
}
<div>{{ message_shallow_reactive }}</div>
<n-button @click="change1">shallowreactive浅层</n-button>
<n-button @click="change2">shallowreactive深层</n-button> 点击后只能在console看到变化;