• 在 Vue.js 中,使用 watch 监听data变量如:对象属性/data变量


     watch 监听对象属性

    Vue.js 中,使用 `watch` 监听对象属性的变化时,应该将属性名作为字符串传递给 `watch` 选项。

    示例如下:

    ```javascript

    1. watch: {
    2.   'addform.isCheck1': function(newValue) {
    3.     console.log(newValue);
    4.     var quantity = this.addform.quantity;
    5.     if (quantity % 2 === 0) {
    6.       quantity = quantity / 2;
    7.     } else {
    8.       quantity = (quantity - 1) / 2;
    9.     }
    10.     this.updateAddChuZhenForm("上午", quantity, newValue);
    11.   },
    12.   'addform.isCheck2': function(newValue) {
    13.     var quantity = this.addform.quantity;
    14.     if (quantity % 2 === 0) {
    15.       quantity = quantity / 2;
    16.     } else {
    17.       quantity++;
    18.       quantity = quantity / 2;
    19.     }
    20.     this.updateAddChuZhenForm("下午", quantity, newValue);
    21.   }
    22. },

    updateAddChuZhenForm函数

    1. //检查数组中是否已存在具有相同 sign 标识的对象。如果存在,它会更新对象的选中状态;如果不存在,它会添加一个新对象。如果取消选中,它会在数组中查找并删除相应的对象。
    2. updateAddChuZhenForm(sign, quantity, isChecked) {
    3. console.log(quantity);
    4. const existingIndex = this.addChuZhenForm.findIndex(
    5. (obj) => obj.sign === sign
    6. );
    7. if (isChecked) {
    8. if (existingIndex === -1) {
    9. this.addChuZhenForm.push({
    10. department_id: this.addform.department_id,
    11. room_id: this.addform.room_id,
    12. doctor_id: this.addform.doctor_id,
    13. inquiry_time: this.addform.inquiry_time,
    14. quantity: quantity,
    15. sign: sign,
    16. });
    17. }
    18. } else {
    19. if (existingIndex !== -1) {
    20. this.addChuZhenForm.splice(existingIndex, 1);
    21. }
    22. }
    23. },

    现在,当 `isCheck1` 或 `isCheck2` 的值发生变化时,相应的 `watch` 函数将被触发。
    ```

    watch监听data变量

    如果你想要监听一个普通变量,而不是 Vue 实例的属性,你可以使用 `watch` 选项以及直接在 `data` 中声明这个变量。

    比如:如果你想监听一个名为 `variableToWatch` 的变量,可以这样做:

    ```javascript

    1. data() {
    2.   return {
    3.     // 其他的data属性
    4.     variableToWatch: false,
    5.   };
    6. },
    7. watch: {
    8.   variableToWatch(newValue) {
    9.     // 在这里可以处理变量变化的逻辑
    10.     console.log('变量的值变为:', newValue);
    11.   }
    12. },

    在上述例子中,我们在 `data` 中声明了一个变量 `variableToWatch`,并在 `watch` 选项中监听了它的变化。当 `variableToWatch` 的值发生变化时,相应的 `watch` 函数将被触发。
    ```

    如果你希望在组件加载后就立即监听该变量,你可以在 `created` 生命周期钩子中手动调用一次 `watch` 函数:

    ```javascript

    1. created() {
    2.   this.$watch('variableToWatch', (newValue) => {
    3.     console.log('变量的值变为:', newValue);
    4.   });
    5. }

    这样,在组件创建后,`variableToWatch` 的初始值也会被监视。
    ```

  • 相关阅读:
    剑指offer—day 11(双指针-1)
    阿里的easyexcal包实现表格动态导出
    Learn Prompt-ChatGPT 精选案例:学习各国语言
    《Docker极简教程》--Docker镜像--Docker镜像的管理
    [附源码]JAVA毕业设计科研项目审批管理系统(系统+LW)
    【C/C++】结构体内存分配问题
    〔020〕Stable Diffusion 之 骨骼姿势 篇
    NLP新手入门指南|北大-TANGENT
    (原创)【MAUI】一步一步实现“悬浮操作按钮”(FAB,Floating Action Button)
    Linux--网络概念
  • 原文地址:https://blog.csdn.net/qq_58647634/article/details/132816883