Vue指令更新模糊输入

Vue directive to update input on blur

我正在尝试实施一个指令,该指令将 trim 模糊事件的输入值:

import { DirectiveOptions } from "vue";

const Autotrim: DirectiveOptions = {
    inserted(el) {
        if(!(el instanceof HTMLInputElement) && !(el instanceof HTMLTextAreaElement)) {
            throw 'Cannot apply v-autotrim directive to a non-input element!';
        }

        el.addEventListener('blur', () => {
           if(el.value)
               el.value = el.value.trim();
        });
    }
};

输入已更新,但模型中的绑定值未更新,并且在组件中其他地方发生任何更改后,它会恢复到未trimmed 状态。

确保模型也得到更新的正确方法是什么?

编辑 这里有一个 codepen link 可以尝试: https://codepen.io/impworks/pen/mddMPyx

您需要触发 input 事件 让 Vue 知道值已更改。

检测到输入值与当前值不同后执行此操作(以避免无限递归)

if (el.value && el.value !== el.value.trim()) {
    el.value = el.value.trim();
    el.dispatchEvent(new Event('input'));
}

参考这个:

  1. 尝试 'input' 活动
  2. 如果上述方法不起作用,请尝试绑定方法和 vnode