vue3中watch的使用?

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档



提示:以下是本篇文章正文内容,下面案例可供参考

一、Watch

vue中watch是用来监听数据的响应式变化,获取数据变化前后的值。
watch的完成参数

watch(监听的数据,副作用函数,配置对象)
watch(data, (newData, oldData) => {}, {immediate: true, deep: true})

二、Watch监听的不同情况

1.监听单个数据

代码如下(示例):

<template>
  <div>
    //监听单个数据
    <input type="text" v-model="text1" name="" id="" />
    <br>
  </div>
</template>

<script>
import { ref, reactive, watch } from "vue";
export default {
  setup() {
    const text1 = ref("");
    // 监听单个属性
     watch(text1,(newVal,oldVal)=>{
         console.log('监听单个数据',newVal,oldVal);
     })
    watch(
      () => stu.name,
      (newVal, oldVal) => {
        console.log("newVal", newVal,"oldVal",oldVal);
      },
      {
        deep: true,
        immediate: true,
      }
    );

    return {
      text1,
    };
  },
};
</script>

<style scoped>
input{
    margin-top: 20px;
}
</style>

2.监听多个属性

代码如下(示例):

<template>
  <div>
   // 监听多个属性
    <input type="text" v-model="text2" name="" id="" />
  </div>
</template>

<script>
import { ref, reactive, watch } from "vue";
export default {
  setup() {
    const text1 = ref("");

    // 监听多个属性
    const text2 = ref("");
    watch([text1,text2],(newVal,oldVal)=>{
        console.log('监听多个数据',newVal,oldVal);
    })
    return {
      text2
    };
  },
};
</script>

<style scoped>
input{
    margin-top: 20px;
}
</style>

3.监听一个对象的问题

<template>
  <div>
    //监听一个对象的问题
    name:<input type="text" v-model="student.name" name="" id="" /> age:<input
      type="text"
      v-model="student.age"
      name=""
      id=""
    />
  </div>
</template>

<script>
import { ref, reactive, watch } from "vue";
export default {
  setup() {
    // 监听一个对象的问题
    const student = reactive({ name: "", age: "" });
    // watch(student, (newVal, oldVal) => {
    //   console.log(newVal);
    //   console.log(oldVal);
    // });

    return {
      student,
    };
  },
};
</script>

<style scoped>
input{
    margin-top: 20px;
}
</style>

3.监听某一个对象的值

<template>
  <div>
    监听某一个对象的值
    name2:
    <input type="text" v-model="stu.name" />
    age2: <input type="number" v-model="stu.age" />
  </div>
</template>

<script>
import { ref, reactive, watch } from "vue";
export default {
  setup() {
    // 监听某一个对象的值
    const stu = reactive({
      name: "",
      age: "",
    });
    watch(
      () => stu.name,
      (newVal, oldVal) => {
        console.log("newVal", newVal,"oldVal",oldVal);
      },
      {
        deep: true,
        immediate: true,
      }
    );
    return {
      stu,
    };
  },
};
</script>

<style scoped>
input{
    margin-top: 20px;
}
</style>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值