强制 Vuetify VTextField 更新值?

问题描述 投票:0回答:1

我正在创建一个自定义 VTextField,它只接受数字并格式化数字。它应该将 VTextField 值更新为过滤和格式化的值,但它不会按预期执行。

我认为原因是当用户输入非数字字符时

display_value
保持不变,并且不会更新/重新渲染组件。无论如何,我可以正确地完成这项工作吗?谢谢。

Nuxt版本:2.14

Vuetify 版本:2

<template>
  <v-text-field
    :value="display_value"
    @input="input($event)"
  >
  </v-text-field>
</template>
<script>
export default {
  data() {
    return {
      display_value: '',
    };
  },
  methods: {
    input(value) {
      let filtered = this.onlyNumbers(value);
      this.$emit('input', filtered);
      this.display_value = Number(filtered).toLocaleString();
      console.log('input=', value);
      console.log('display_value=', this.display_value);
    },
    onlyNumbers(value) {
      value = String(value);
      return value.replace(/\D+/g, '');
    }
  }
}
</script>

vue.js vuejs2 nuxt.js vuetify.js
1个回答
1
投票

这有点黑客行为。

<template>
  <v-text-field
    ref="inputRef"
    :value="display_value"
    @input="input($event)"
  >
  </v-text-field>
</template>
<script>
export default {
  data() {
    return {
      display_value: '',
    };
  },
  methods: {
    input(value) {
      let filtered = this.onlyNumbers(value);
      this.$emit('input', filtered);
      this.display_value = Number(filtered).toLocaleString();
      console.log('input=', value);
      console.log('display_value=', this.display_value);
      this.$refs.inputRef.lazyValue = this.display_value;
    },
    onlyNumbers(value) {
      value = String(value);
      return value.replace(/\D+/g, '');
    }
  }
}
</script>

这里是演示:https://codepen.io/init-qy/pen/bGOzLMQ

© www.soinside.com 2019 - 2024. All rights reserved.