watch的基本使用

<template>
  <div class="watch-container">
    <input type="text" v-model="num" />
    <input type="text" v-model="obj.age" />
    <button @click="clickFn">点击加1</button>
    <button @click="clickFn1">点击年龄改变</button>
    <button @click="clickFn2">点击年龄加1</button>
  </div>
</template>

<script>
export default {
  name: "watch",
  data() {
    return {
      num: 3,
      obj: {
        age: 18,
      },
    };
  },
  watch: {
    // 基础用法
    // num(newVal, oldVal) {
    //   console.log(newVal, oldVal);
    // },
    age(newVal, oldVal) {
      console.log(newVal, oldVal);
    },
    // 完整写法
    num: {
        handler(newVal, oldVal) {
            console.log(newVal, oldVal);
        },
        // 第一次赋值就执行
        immediate: true,
        // 当要监听对象或数组的时候需要添加deep:true属性
    }
  },
  methods: {
    clickFn() {
      this.num += 1;
    },
    clickFn1() {
      if (this.obj.age >= 18) {
        console.log("成年了");
      } else {
        console.log("没成年");
      }
    },
    clickFn2() {
        this.obj.age++
    }
  },
};
</script>

<style>
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值