观察计算值时不会触发 Vue 观察器

时间:2021-01-15 17:07:39

标签: javascript vue.js vue-reactivity

我有一个具有计算值的组件和该计算值的观察者。当计算值更新时,观察者有时不会被触发。

我无法提供重现该问题的方法,因为它在我的机器上运行,并且在大多数情况下(但并非总是如此)也适用于我们的生产版本。

我的代码类似于:

new Vue({
  el: "#app",
  data() {
    return {
      duckNames: ["Donald", "Mike"],
      llamas: [{ name: "Joe" }, { name: "Kamala" }],
      
      selectedAnimalName: "",
      lastSelectedLlamas: [],
      isLoading: false,
    };
  },
  computed: {
    selectedLlama() {
      return this.llamas.find(llama => llama.name === this.selectedAnimalName);
    },
  },
  watch: {
    selectedLlama(newLlama) {
      if (newLlama) {
        this.lastSelectedLlamas.unshift(newLlama);
      }
    },
    lastSelectedLlamas(newArr) {
      if (newArr.length > 2) {
        this.lastSelectedLlamas = newArr.slice(0, 2);
      }
    },
  },
  methods: {
    async selectAnimal(name) {
      this.selectedAnimalName = name;
      this.isLoading = true;
      await this.fetchSomeData();
      this.isLoading = false;
    },
    fetchSomeData() {
      return new Promise(res => setTimeout(res, 1000));
    },
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button
    v-for="duckName in duckNames"
    @click="selectAnimal(duckName)"
  >
    {{ duckName }}
  </button>
  <br>
  
  <button
    v-for="llama in llamas"
    @click="selectAnimal(llama.name)"
  >
    {{ llama.name }}
  </button>
  <br>
  
  Selected animal: {{ selectedAnimalName }}<br>
  Last selected llamas: {{ lastSelectedLlamas }}<br>
  
  <span v-if="isLoading">
    Loading...
  </span>
</div>

在示例中,观察者用最后选择的值填充了一个数组。在生产版本中,有时不会发生。调试确认没有调用监视处理程序本身。

我的版本(知道其中的相关内容):

"dependencies": {
  "html-loader": "0.5.5",
  "vue": "2.6.11",
  "vue-color": "2.7.0",
  "vue-router": "3.1.3",
  "vuetify": "2.1.14",
  "vuex": "3.0.1"
},
"devDependencies": {
  "@vue/cli-plugin-babel": "3.11.0",
  "@vue/cli-plugin-eslint": "3.11.0",
  "@vue/cli-plugin-unit-jest": "3.11.0",
  "@vue/cli-service": "4.2.3",
  "babel-core": "7.0.0-bridge.0",
  "babel-plugin-syntax-dynamic-import": "6.18.0",
  "babel-preset-env": "1.7.0",
  "html-webpack-plugin": "3.2.0",
  "vue-cli-plugin-html-replace": "1.3.0",
  "vue-cli-plugin-vuetify": "0.5.0",
  "vue-template-compiler": "2.6.11",
  "vuetify-loader": "1.4.3",
  "webpack": "4.41.2"
}

0 个答案:

没有答案