强制更新 Vuetify 文本字段值

Force Vuetify text field value to update

在下面的 codesandbox 中,我试图实现多个数字输入,以便它们的总和永远不会超过 max

我已经在项目上成功实现了这个,你可以在Vue工具中看到传递给<v-text-field>组件的值是正确的值,但是渲染值不断增加超过max.

我曾尝试基于旧对象创建一个新对象,以便 Input 组件识别更改的道具并强制重新渲染,但这不起作用。我已经尝试过明确地强制重新渲染组件(以及 v-text-field 本身的引用)但仍然没有骰子。几乎到处都尝试过使用和不使用 $nextTick...

https://codesandbox.io/s/intelligent-worker-rho9wo?file=/components/Input.vue

编辑:@input 事件上没有 preventDefault,因为它只是原始文本。 @change 仅在远离视野时开火,到那时就为时已晚。相反,尝试将逻辑放在 @mousedown@keydown 事件上为时过早,因为此时 event.target.value 仍然是先前的输入。

检查我从你的项目中分叉出来的这个 codesandox:https://codesandbox.io/s/stack-72330576-custom-inputnumber-v-for-max-validation-9mvoed?file=/pages/index.vue

我过去已经制作了一个自定义的 InputNumber 组件,所以我只是使用我的组件,希望没关系。我只是稍微修改一下以使其符合您的要求。而不是使用 html 输入类型数字按钮,如果您实现自己的 decrease/increase 按钮会更好,这样您可以更好地控制您的输入。

最后,为了实现所需的行为,我不得不扩展 VTextField 并覆盖 onInput 行为

<script>
import { VTextField } from "vuetify/lib/components/VTextField";
export default {
  name: "MyTextField",
  extends: VTextField,
  methods: {
    onInput(e) {
      const target = e.target;
      this.$emit("input", target.value);
      this.$refs.input.blur();
    },
  },
};
</script>

https://codesandbox.io/s/nice-sammet-zr7qr0?file=/components/MyTextInput.vue:0-294