gpt4 book ai didi

vue.js - Vue指令更新模糊输入

转载 作者:行者123 更新时间:2023-12-01 12:04:53 26 4
gpt4 key购买 nike

我正在尝试实现一个指令,该指令将在模糊事件上修剪输入的值:

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();
});
}
};

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

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

EDIT 这里有一个 codepen 链接可以尝试: 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'));
}

关于vue.js - Vue指令更新模糊输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58590628/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com