vue3Watch监听RefImpl对象的说明

vue3Watch监听RefImpl对象的说明

  • watch监听RefImpl对象

watch监听RefImpl对象

<script>
import { ref, reactive, watch } from "vue";
export default {
  name: "Demo",
  setup() {
    // 数据
    let sum = ref(0);
    let msg = ref("你好啊");
    let person = ref({
      name: "张三",
      age: 18,
      job: {
        job1: {
          salary: 20,
        },
      },
    });
    // watch监听的是RefImpl,不能加.value, 
    // 添加value取出的就是真正的值数字0,无法监听!!
    watch(sum, (newValue, oldValue) => {
      console.log("sum", newValue, oldValue);
    })

    // 通过ref传对象,内部会调用reactive方法,将proxy代理对象赋值给 RefImpl.value所以需要监听value的值
     watch(person.value, (newValue, oldValue) => {
       console.log("person.value", newValue, oldValue);
     })

    // 也可以配置,deep为true解决问题
    watch(person, (newValue, oldValue) => {
      console.log("person.value", newValue, oldValue);
    }, {deep: true})

    return {sum,msg,person,};
  },
};
</script>

你可能感兴趣的:(vue3,javascript,vue,vue.js)