【问题标题】:Vue2 watch Set Not WorkingVue2手表设置不工作
【发布时间】:2018-06-18 13:49:50
【问题描述】:

我有一个简单的 Vue 应用程序,当您单击“添加到集合”按钮时,它应该向集合中添加一个数字 --

https://codepen.io/jerryji/pen/mKqNvm?editors=1011

<div id="app">
  <input type="number" placeholder="enter a number" v-model="n">
  <button type="button" @click.prevent="addToSet()">Add to Set</button>
</div>

new Vue({
  el: "#app",
  data: {
    n: null,
    nSet: new Set()
  },
  methods: {
    addToSet: function() {
      this.nSet.add(this.n);
      console.log(this.n + ' added to Set');
    }
  },
  watch: {
    nSet: function (newVal, oldVal) {
      console.log(newVal);
    }
  }
});

为什么watch在控制台中没有任何记录?

【问题讨论】:

  • 您有什么理由使用Set 而不是Array?如果唯一目的是确保唯一性,您可以在推送前轻松检查indexOf。 AFAIK 没有简单的方法来观察 Set 的变化。
  • 因为实际代码中需要Set。 codepen 只是一个精简的例子。但我明白你的意思。谢谢
  • 想知道 Set 在 Vue 组件中是否是非响应式的。

标签: javascript vuejs2 codepen


【解决方案1】:

使用Set 上的.values() 方法保存并重新Setting Set 对我有用,我不必使用$forceUpdate

使用$forceUpdate 可能是更明智的选择。在过去的某些用例中,我发现强制组件更新是有问题的。

new Vue({
  el: "#app",
  data: {
    n: null,
    nSet: new Set()
  },
  methods: {
    addToSet: function() {
      let set = this.nSet;
      let newSet = set.add(this.n)
      this.nSet = new Set(newSet.values())
    }
  },
  watch: {
    nSet: function (newVal, oldVal) {
      console.log('newVal', ...newVal);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>


<div id="app">
  <input type="number" placeholder="enter a number" v-model="n">
  <button type="button" @click.prevent="addToSet()">Add to Set</button>
  <p>n = {{ n }}</p>
</div>

【讨论】:

    【解决方案2】:

    Vue 添加了special handling for Arrays,但不适用于 Sets。因此,Vue 不会自动检测对 Set 成员资格的更改。不过,您可以强制更新

      this.nSet.add(this.n);
      this.$forceUpdate();
    

    【讨论】:

      【解决方案3】:

      这是因为 Vue 不支持 Set、Map、WeakSet 和 WeakMap。这是因为浏览器不能很好地支持这些结构。特别是弱地图。但是……他们决定支持这些结构。也许在版本 3 - 当他们决定放弃对旧浏览器的支持时。因此,现在使用一个对象,使用Vue.$set() 添加属性并使用deep: true 观察变化。

      【讨论】:

        猜你喜欢
        • 2021-09-13
        • 2022-08-05
        • 2019-06-12
        • 1970-01-01
        • 2014-12-10
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多