VUE3-watch侦听

文章讲述了Vue3中计算属性和watch侦听属性的概念与区别。计算属性用于创建新属性并基于其他数据自动更新,而watch则持续监控特定数据变化并在变化时执行回调。在Vue3的例子中,展示了如何使用ref和watch监听多个属性的变化。同时,提到了在Vue2中watch的写法,包括简写和完整形式。

VUE3-watch侦听

计算属性与侦听属性的区别

  • computed 计算属性: 需要声明一个新的属性,得到新的数据。
  • watch 侦听属性/监视属性:一直在监视某个data数据的变化,则watch中的handler函数会被调用。

写法

vue3

<template>
  <div>{{counter}}</div>
  <button @click="counter++">计算器++</button>
  <div>{{counter2}}</div>
  <button @click="counter2++">计算器2++</button>
</template>

<script>
  import {
    ref,
    watch
  } from 'vue'
  export default {
    setup() {
      // data
      let counter = ref(1)
      let counter2 = ref(100)
      // watch
      // 被监视的数据需要具有响应式
      // watch(counter, (newValue, oldValue) => {
      //   console.log('计算器', newValue, oldValue);
      // }, {immediate: true, deep: true})

      // watch(counter2, (newValue, oldValue) => {
      //   console.log('计算器2', newValue, oldValue);
      // }, {immediate: true})

      // 采用数组的方式,一次监视多个属性
      watch([counter, counter2], (newValue, oldValue) => {
        console.log(newValue, oldValue); // newValue和oldValue都是数组
      })
      // 返回一个对象
      return {
        counter,
        counter2
      }
    }
  }
</script>

vue2

<template>
  <div>{{counter}}</div>
  <button @click="counter++">计数加</button>
</template>

<script>
  export default {
    // vue2写法
    data() {
      return {
        counter: 1
      }
    },
    watch: {
      // 简写形式
      // 监视的是counter属性
      // 注意:被监视的属性必须具有响应式的,才能监视。
      // counter(newValue, oldValue){
      //   console.log(newValue, oldValue);
      // }

      // 完整写法
      counter: {
        immediate: true, // 开始的时候,立即执行一次handler
        deep: true, // 启用深度监视
        handler(newValue, oldValue) {
          console.log(newValue, oldValue);
        }
      }
    }
  }
</script>
涉及内容

VUE3、ref、watch侦听

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值