VUE3-shallowReactive函数与shallowRef函数(14)

<template>
  <h2>当前的x.y值是:{
   
   { x.y }}</h2>
  <button @click="x={y: 888}">点我替换x</button><!-- 整体替换当然有响应式 -->
  <button @click="x.y++">点我x.y++</button><!-- 内部的x没有响应式处理,所以此按钮失效 -->
  <hr>

  <h2>姓名:{
   
   { name }}</h2>
  <h2>年龄:{
   
   { age }}</h2>
  <h2>薪资:{
   
   { job.j1.salary }}K</h2>
  <button @click="name+='~'">修改姓名</button>
  <button @click="age++">增长年龄</button>
  <button @click="job.j1.salary++">涨薪</button><!-- 涨薪按钮失效 -->
</template>

<script>
import {
     
     toRefs, shallowReactive, shallowRef} from 'vue'

export default {
     
     
  name: 'App',
  setup() {
     
     
    // 只考虑第一层数据的响应式
    let person = shallowReactive({
     
     
      name: '张三',
      age: 18,
      job: {
     
     
        j1: {
     
     
          salary: 20
        }
      }
    })

    // 不进行对象的响应式处理
    let x = shallowRef({
     
     
      y: 0
    })
    console.log(x) // RefImpl {...}
    console.log(x.value) // {y: 0}

    return {
     
     
      x,
      ...toRefs(person)
    }
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/gty204625782/article/details/123410936