【问题标题】:trigger watch function in Vue 3 composition Api在 Vue 3 组合 Api 中触发监视功能
【发布时间】:2021-04-18 16:32:09
【问题描述】:

我已经在设置中设置了这个反应值

const refValue = ref('foo');

并为其设置watch 函数


     watch(refValue, function() {
       console.log("activaded")
    
    });

如果我手动更改值,watch 函数将不会被激活,

只有在添加改变值的函数时才会激活

 const changeValue = function changedValue() {
      console.log("fired");

      return refValue.value = 12;
    }

为什么只有在使用函数更改值时才会触发watch,
我认为 const refValue = ref('foo'); 是被动的,所以watch 应该检测到所有更改

import { ref,watch } from 'vue';

export default {
  setup() {
    
    const refValue = ref('foo');
 

     watch(refValue, function() {
       console.log("activaded")
    
    });

    const changeValue = function changedValue() {
      console.log("fired");

      return refValue.value = 12;
    }



    return {
      refProp: refValue,
      changeFuncton: changeValue
     
    };
  },

};

【问题讨论】:

    标签: javascript watch vuejs3 vue-composition-api


    【解决方案1】:

    尝试immediate 选项并使用函数作为返回观察到的属性的第一个参数:

       watch(()=>refValue, function() {
           console.log("activaded")
        
        },{immediate:true});
    

    【讨论】:

      【解决方案2】:

      refValue 类型是一个对象。

      vue 监视 refValue 对象 reference 变化,而不是属性变化

      【讨论】:

        猜你喜欢
        • 2021-05-25
        • 2021-06-22
        • 2011-09-06
        • 1970-01-01
        • 2017-03-05
        • 1970-01-01
        • 2018-12-29
        • 2022-07-19
        • 2021-02-03
        相关资源
        最近更新 更多