reactive用来绑定复杂的数据类型, 例如:对象、数组。
它是不可以绑定普通的数据类型这样是不允许 会给我们报错
<script setup>
import {
reactive } from 'vue';
const data = reactive({
name: 'John',
age: 30,
address: {
city: 'New York',
state: 'NY'
}
});
data.name = "张三"
</script>
数组异步赋值页面是不会变化的因为会脱离响应式
let data = reactive([])
setTimeout(() => {
data = [1, 2, 3]
console.log(data);
},1000)
ref和reactive的区别
- ref支持所有类型,reactive只支持引用数据类型 Array、Object、Map、Set
- ref取值、赋值,都需要加 .value,reactive则不需要
- reactive使用proxy代理,不能直接赋值,否则会破坏响应式对象
解决方案:
- 使用push方法
import {
reactive } from 'vue'
let data = reactive([])
setTimeout(() => {
const arr = [1, 2, 3]
data.push(...arr)
console.log(data);
},1000)
- 在外层包裹一层对象
let data = reactive({
list:[]
})
setTimeout(() => {
const arr = [1, 2, 3]
data.list = arr;
console.log(data);
},1000)
readonly
拷贝一份proxy对象将其设置为只读,如果reactive
中的数据发生变化readonly
也会改变
import {
reactive ,readonly} from 'vue'
const person = reactive({
count:1})
const copy = readonly(person)
//person.count++
copy.count++
shallowReactive
和shallowRef
一样只能对浅层的数据 如果是深层的数据只会改变值 不会改变视图
<template>
<div>
<div>{
{
state }}</div>
<button @click="change1">test1</button>
<button @click="change2">test2</button>
</div>
</template>
<script setup>
import {
shallowReactive } from 'vue'
const obj = {
a: 1,
first: {
b: 2,
second: {
c: 3
}
}
}
const state = shallowReactive(obj)
function change1() {
state.a = 7
}
function change2() {
state.first.b = 8
state.first.second.c = 9
console.log(state);
}
</script>