vue指令设置input框的值和data里的值不同步

标签 用的v-model.lazy


        <el-form-item label="Price or Price Range:" prop="description.listedMinPrice">
          <el-input class="range-input money-input" v-model.lazy="form.description.listedMinPrice" v-money-format placeholder="0"></el-input>
        </el-form-item>

指令

export const moneyFormat: DirectiveOptions = {
  bind: (el, binding) => {
    // 判断是否是input元素
    const els = el.tagName.toLocaleUpperCase() === 'INPUT' ? el : el.querySelector('input') ? el.querySelector('input') : null
    let _el!: IElementInput | HTMLInputElement
    if (els) {
      _el = els as IElementInput
    } else {
      throw new Error('v-money-format requires 1 input')
    }
    const opt = Object.assign({}, options, binding.value ? binding.value : {})
    const regStr = '/^$*+?.|'
    const inRegStr = regStr.includes(opt.thousands) ? `\\${opt.thousands}` : opt.thousands
    const thousandsReg = new RegExp(inRegStr, 'g')
    if (!_el.isFocus) {
      _el.value = moneyFormatFn(_el.value, opt.precision, opt.thousands)
      console.log('isFocus', _el.value)
    }
    _el.onfocus = (): void => {
      _el.isFocus = true
      _el.value = _el.value.replace(thousandsReg, '')
      console.log('onfocus', _el.value)
    }
    _el.onblur = (): void => {
      _el.isFocus = false
      _el.value = moneyFormatFn(_el.value, opt.precision, opt.thousands)
      console.log('onblur', _el.value)
    }
    _el.oninput = (): void => {
      _el.value = _el.value.replace(thousandsReg, '').replace(/^\D*([1-9]\d*\.?\d{0,2})?.*$/, '$1')
      console.log('oninput', _el.value)
    }
  },
}

输入的是123.456
在input和blur的事件时 将value = 123.45
但data里面的数据还是 123.456

image.png

阅读 3.9k
2 个回答

你在指令里改变了 input DOM 的 el.value 值,但是 v-model 绑定的 form.description.listedMinPrice 值不会随之改变,建议还是对 vue 内绑定的值进行操作比较好。

你也许需要这个api nextTick ,更新视图的时候需要马上用到新的数据,就需要用到它。
文档

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题