自学内容网 自学内容网

watch监听vue2与vue3的写法

watch的属性值

handler:回调函数, 即监听到变化时应该执行的函数,可以是单独的函数或带有 immediate 和 deep 属性的对象
    watch: {
      someProperty: function(newVal, oldVal) {
        // 处理逻辑
      }
    }


deep: 其值是true或false, 当属性值是对象或数组时,深度观察会监控对象内部所有层级的变化。
    watch: {
      someObject: {
        handler(newVal, oldVal) {
              // 处理逻辑
        },
        deep: true
      }
    }


immediate: 值是true或false,首次绑定时立即执行回调函数
    watch: {
      someProperty: {
        handler(newVal, oldVal) {
          // 处理逻辑
        },
        immediate: true
      }
    }

vue2写法:

//基本用法
  watch:{
    avatar(navl,oval){
        console.log(navl,'navl');
        console.log(oval,'oval');
    }
  },
//深度监听 
watch: {
    user: {
      handler(nval,oval) {
         console.log(nval,oval);
      },
      deep: true,
    }
  },
//立即执行
watch: {
    user: {
      handler(nval,oval) {
         console.log(nval,oval);
      },
      immediate: true
    }
  },
//观察数组中特定项的变化
  watch: {
    'user[0]': function(newVal, oldVal) {
      console.log('user[0] changed from', oldVal, 'to', newVal);
    }
//监听多个数据源
  watch: {
    property1(newVal, oldVal) {
      console.log('property1 changed from', oldVal, 'to', newVal);
    },
    property2(newVal, oldVal) {
      console.log('property2 changed from', oldVal, 'to', newVal);
    }
  }

vue3写法:

import { watch } from 'vue';
//基本用法
watch(avatar, (newVal, oldVal) => {
   console.log('avatarchanged from', oldVal, 'to', newVal);
});

//深度管察
watch(
   () => user,
   (nval,oval) => {
      console.log(val, oval)
   },
    { deep:true },
)

//立即执行
watch(
   () => user,
   (nval,oval) => {
      console.log(val, oval)
   },
    { immediate: true },
)

//使用回调函数对象
watch(
   someProperty,
    {
       handler(newVal, oldVal) {
        console.log('someProperty changed from', oldVal, 'to', newVal);
     },
       immediate: true,
       deep: true
      }
    );


原文地址:https://blog.csdn.net/m0_45827438/article/details/140541119

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!