shallowReactive 和 shallowRef

shallowReactive函数

  • 只将对象的第一层属性变成响应式
<template>
  <div>姓名 {{name}}</div>
  <div>年龄 {{age}}</div>
  <div>工资 {{job.j1.salary}}</div>
  <div>
    <button @click="name+='~'">修改姓名</button>
    <button @click="age++">增长年龄</button>
    <button @click="job.j1.salary++">增加工资</button>
  </div>
</template>

<script>
import { toRefs, shallowReactive, } from "vue";
export default {
  name: 'Demo',
  setup() {
    let person = shallowReactive({
      name: '张三',
      age: 18,
      job: {
        j1: {
          salary: 3000
        }
      }
    })
    return {
      ...toRefs(person)
    }
  }
}
</script>
  • person 对象的 name、age、job 是响应式的,job属性里面的内容不是响应式的

shallowRef函数

<template>
  <div>{{x.y}}</div>
  <div>{{y}}</div>
  <div>
    <button @click="x.y++">x.y 增加</button>
    <button @click="y++">y增加</button>
  </div>
</template>

<script>
import {shallowRef} from 'vue'

export default {
  setup() {
    let x = shallowRef({
      y: 0
    })
    let y = shallowRef(0)
    return {
      x,
      y,
    }
  }
}
</script>
  • 如果给  shallowRef 传递是基本类型数据则与  ref 函数处理一样
  • 如果给  shallowRef 传递的是一个对象,那么这个对象  .value 赋值是响应式的,修改这个对象 x 里面的某个属性则不是响应式的
posted @ 2022-01-30 20:05  霸哥yyds  阅读(193)  评论(0)    收藏  举报