首页 > 解决方案 > 再次更改值而不触发手表

问题描述

我试图找到一种解决方法来解决在相同属性的手表内更改 2 向绑定的问题,避免再次调用手表。例如:

<select v-model="language">
  <option ... />
</select>


watch:{
  language(newVal // 'fr' , oldVal // 'en'){
    if(condition){
      // do something
    } else {
      // roll back to the old language
      this.language = "en" // will call watch again.

      // Looking for something like this:
      // Vue.set(this, 'language', 'en', { watch: false })
    }
  }
}

我考虑过使用@change,但这无济于事,因为我必须使用对象而不是普通值再次设置值。

我知道我可以使用其他 2-way 属性并将其用作标志,但我寻找更优雅的东西。

标签: vuejs2

解决方案


为什么首先回滚用户的选择?您可以使用 acomputed property提供有效选项的过滤列表,以提供更好的用户体验。

下面的示例仅允许您选择en条件复选框是否为真。

Vue.config.productionTip = false;

new Vue({
  el: '#app',
  template: `
    <div>
      <p>Condition: <input type="checkbox" v-model="condition" /></p>
      <p>Selection: {{selection}}</p>
      <select v-model="selection">
        <option v-for="opt in filteredOptions" :key="opt.value" :value="opt.value">{{opt.label}}</option>
      </select>
    </div>
  `,
  data: () => ({
    selection: undefined,
    condition: true,
    options: [
      { label: 'English', value: 'en' },
      { label: 'French', value: 'fr' },
      { label: 'Spanish', value: 'es' },
    ],
  }),
  computed: {
      filteredOptions() {
        return this.condition ? this.options.filter(x => x.value === 'en') : this.options;
      }
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>


推荐阅读