Reactive的使用(reactive 和 shallowReactive使用上区别)

与Reactive相关可用的包括reactive、shallowReactive,reactive API可以响应式更新视图,shallowReactive浅层更新视图。外加readonly API

Reactive

从vue导出,用reative包裹对象{name:大漂亮}

<template>
    <div>
    {
   
   {person.name}}
    </div>
</template>

<script setup lang='ts'>
// <!-- rective 不可以绑定普通类型 -->
import {
      
      reactive} from 'vue'
let person=reactive({
      
      
    name:'大漂亮'
})
person.name="小漂亮"
</script>

shallowReactive

视图上只更新浅层的,但是数据会更新

例1
<template>
    <div v-for="index in person">
        <div>{
   
   {index}}</div>
    </div>
    <button @click="add">数组加一</button>
</template>
import {
    
     shallowReactive } from 'vue'
let person=shallowReactive<number[]>([])
const arr=[1,2,3];
person.push(...arr);
function add(){
    
    
    console.log(person);
    for(let i=0;i<person.length;i++){
    
    
        console.log(person[i]++)
    }
}

结果:点击button,person数组里面的值会加一,视图会同步更新

例2
<template>
    <div>
      <div>{
   
   { state }}</div>
      <button @click="change1">test1</button>
      <button @click="change2">test2</button>
    </div>
  </template>
<script setup lang='ts'>
// <!-- rective 不可以绑定普通类型 -->
import {
      
      reactive} from 'vue'
//只能对浅层的数据 如果是深层的数据只会改变值 不会改变视图
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>

结果:
页面原始显示
{ “a”: 1, “first”: { “b”: 2, “second”: { “c”: 3 } } }
点击text1视图结果为:
{ “a”: 7, “first”: { “b”: 2, “second”: { “c”: 3 } } }
点击text2视图结果为
{ “a”: 7, “first”: { “b”: 2, “second”: { “c”: 3 } } }
控制台输出为:
{
“a”: 7,
“first”: {
“b”: 8,
“second”: {
“c”: 9
}
}
}
由此可见,使用shallowReactive深层次数据会更新,但不会更新到视图上。
如果将代码改为

<script>
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>

点击test1视图结果为{ “a”: 7, “first”: { “b”: 2, “second”: { “c”: 3 } } }
点击test2视图结果为{ “a”: 7, “first”: { “b”: 8, “second”: { “c”: 9 } } }
由此可见,reactive会将视图全部更新。

readonly使用示例

import {
    
    readonly} from 'vue'
const person = reactive({
    
    count:1})
const copy = readonly(person)
 
 person.count++
 
// copy.count++  直接报错

是能显示到视图上,不能做更改。

猜你喜欢

转载自blog.csdn.net/weixin_42491648/article/details/128046132
今日推荐