Vue3中的 reactive 详解

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的区别
  1. ref支持所有类型,reactive只支持引用数据类型 Array、Object、Map、Set
  2. ref取值、赋值,都需要加 .value,reactive则不需要
  3. reactive使用proxy代理,不能直接赋值,否则会破坏响应式对象

解决方案:

  1. 使用push方法
import {
    
     reactive } from 'vue'
let data = reactive([])
setTimeout(() => {
    
    
  const arr = [1, 2, 3]
  data.push(...arr)
  console.log(data);
  
},1000)
  1. 在外层包裹一层对象
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> 

猜你喜欢

转载自blog.csdn.net/weixin_53156345/article/details/134004377