【问题标题】:Start watcher after created() is donecreated() 完成后启动观察者
【发布时间】:2021-10-19 07:20:48
【问题描述】:

我的目标是在创建组件时首先设置一个数据属性,然后在该属性上设置一个观察者。我正在努力解决的问题是观察者在 created 方法中捕获了初始属性更改,但这不是我想要的。我宁愿仅在在 created() 中进行初始更改后观看数据属性。

export default {
 name: 'testComponent',

 data() {
  return {
   testValue: 1;
  }
 },

 watch: {
  testValue() {
   console.log('watcher catches!');
  },

 created() {
   console.log(this.testValue);
   this.testValue = 2;
   console.log(this.testValue);
 }
}

// CONSOLE OUTPUT:  1 -> watcher catches! -> 2

你能告诉我如何实现这样的行为吗?

【问题讨论】:

    标签: vue.js vue-component vuejs3


    【解决方案1】:

    不知道你为什么想要这样,但你可以简单地这样做:

    export default {
     name: 'testComponent',
    
     data() {
      return {
       ready: false,
       testValue: 1
      }
     },
    
     watch: {
      testValue() {
       if (!this.ready) return;
       console.log('watcher catches!');
      },
    
     created() {
       this.testValue = 2;
       this.ready = true;
     }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-20
      • 1970-01-01
      • 2015-05-11
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 2021-02-20
      相关资源
      最近更新 更多