首页 > 解决方案 > Vue:如何避免在mounted() 中使用setTimeout 来等待道具可用?

问题描述

我发现自己经常使用 setTimeout 来等待初始数据被加载并在我的 Vue 组件中可用。通常,我会尝试访问初始数据,但它还没有准备好。例子:

data: {
  return() {
     name: null
  }
},
props: {
    otherName: {type: String}
},
mounted() {

     if (this.otherName == "Bob" {
        // do something
     }
}

这种模式行得通吗?我正在考虑这个问题,但这种火灾多久会发生一次?我会反复开火吗?至少在已安装的情况下,我知道它只发生一次且仅发生一次。

computed: {
   getOtherName() {
       return this.otherName;
   }
},
watch: {
   getOtherName(newValue, oldValue) {  
       if (oldValue != null && newValue == "Bob) {
          //do something -- the prop will be null though so I use a setTimeout to wait for it to be available and not null
       }
   }
}

标签: vue.jsvuejs2

解决方案


每次检测到属性更改时,都会触发被监视的属性,因此该解决方案还没有完全准备好。不过,最好不要使用超时,因为这很愚蠢,尤其是因为您违背了 Vue 作为 MVVM 框架的目的。

如果你想有一个初始化步骤,那么你有两个合理的选择:

  1. 您可以提前安装组件,然后跟踪initialized标志以确定您是否已执行该初始化步骤。
  2. 您可以推迟安装组件,直到您的数据首先准备好。

选项 1 看起来像这样:

data() {
    return {
        initialized: false
    };
},
watch: {
    getOtherName(newValue, oldValue) {
        if(this.initialized || oldValue !== null) {
            return;
        }

        // Perform initialization logic.

        this.initialized = true;
    }
}

选项 2 看起来像这样:

// HTML template
<my-component v-if="data_source !== null" :otherName="data_source"></my-component>

// JS
mounted: {
    // Perform initialization logic.
}

推荐阅读