Vue2 手表设置不起作用 [英] Vue2 watch Set Not Working

查看:24
本文介绍了Vue2 手表设置不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<input type="number" placeholder="输入数字" v-model="n"><button type="button" @click.prevent="addToSet()">添加到集合</button>

新的 Vue({el: "#app",数据: {n:空,nSet: 新的 Set()},方法: {addToSet: 函数() {this.nSet.add(this.n);console.log(this.n + ' 添加到 Set');}},手表: {nSet: 函数 (newVal, oldVal) {控制台日志(新值);}}});

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

解决方案

Vue 添加 对数组的特殊处理,但不适用于集合.因此,Vue 不会自动检测 Set 成员资格的更改.不过你可以强制更新

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

I have a simple Vue app that is supposed to add a number to a Set when you click the "Add to Set" button --

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);
    }
  }
});

Why is nothing logged in the console by the watch?

解决方案

Vue adds special handling for Arrays, but not for Sets. As a result, Vue doesn't automatically detect changes to Set membership. You can force an update, though

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

这篇关于Vue2 手表设置不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆