vue数据更新视图不实时更新的问题,这是为什么啊?

环境

vue + elemntUI

相关代码

https://codepen.io/eeeecw/pen...

具体情景

在输入框的 change 事件里,我修改了输入框的双向帮定值,但不是每次都显示在输入框里。
比如上面代码,输入框不支持小数,每次输入后,我都会在 change 事件里把数字转成整数,但是显示的值还是原来的值
但是如果在 change 事件里写一个 setTimeout 去把数字转成整数,就回成功把最新值渲染出来。。。
这是为什么?求原理?或者有什么更好的解决办法?

阅读 4.3k
4 个回答

应为num1初始值是1,你输入1.3655后,通过Math.floor(this.value.num1)计算之后还是num1还是1,el-input-number内部的watch没有监听到变化,el-input-number相关代码如下:

  watch: {
    value: {
      immediate: true,
      handler: function handler(value) {
        var newVal = value === undefined ? value : Number(value);
        if (newVal !== undefined) {
          if (isNaN(newVal)) {
            return;
          }
          if (this.precision !== undefined) {
            newVal = this.toPrecision(newVal, this.precision);
          }
        }
        if (newVal >= this.max) newVal = this.max;
        if (newVal <= this.min) newVal = this.min;
        this.currentValue = newVal;
        this.$emit('input', newVal);
      }
    }
  },

不要用@change
改成@input

建议用computed

可以用下面的方法让它实时更新,原因可以参考https://cn.vuejs.org/v2/guide...

this.$nextTick(function () {
    this.value.num1 = Math.floor(this.value.num1)
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题