[英]Vue why is value in input -- respresented as empty string in v-model?
嘿,我正在为整数开发自定义输入组件,有 2 种基于acceptNegatives
道具的模式,表明它是否应该接受负数,问题是我当前的实现允许添加多个-
符号,而组件应该也接受负面影响。
我想要完成的是在 prop acceptNegatives="true"
上,组件应该接受输入或粘贴值,如-2
或2
而不是-0
或“--”、“--2”,因为这些值被视为空出于某种原因的字符串。
输入组件的 Html 它使用Buefy
的默认输入
<template>
<b-input
:placeholder="placeholder"
:value="value"
@input="handleChange"
@paste.native="handlePaste"
@keydown.native="handleKeyDown"
@mousewheel.native="$event.preventDefault()"
@blur="handleBlur"
:icon-right="iconRight"
:name="name"
autocomplete="off"
:type="type"
></b-input>
</template>
handleKeyDown(event) {
const { key } = event;
if (this.acceptNegatives && this.isAdditionalKeyAllowed(event)) {
this.$emit("keydown", key);
return;
}
if (this.isAdditionalKeyAllowed(event) || this.isValidNumber(key)) {
return this.allowPositiveNumbersOnly(event);
}
event.preventDefault();
},
isAdditionalKeyAllowed(event) {
const allowedKeyWithoutMeta = Object.values(ALLOWED_KEYS).includes(keyCode);
if (this.hasAlreadyMinusSign(event.target.value, key)) {
return false;
}
if (this.acceptNegatives) {
return (
allowedKeyWithoutMeta || key === "-"
);
}
return allowedKeyWithoutMeta;
},
hasAlreadyMinusSign(value, key) {
return this.acceptNegatives && value.includes("-") && key === "-";
},
我还准备了一些演示它在 Vue 中是如何工作的。 目前我不知道如何解决这个问题。 我应该使用观察者还是应该以某种方式计算值? 谢谢你的建议。
您需要一种方法来去除'------1'
的可能性,最简单的方法是使用一些正则表达式:
inputVal() {
// Regex that replaces all occurrences of "-" except the last
return this.value.replace(/[-](?=.*[-])/g, "");
}
然后将输入绑定到此计算并使用getter 和 setter ,如下所示:
inputVal() {
get() {
// Regex that replaces all occurrences of "-" except the last
return this.value.replace(/[-](?=.*[-])/g, "");
},
set(val) {
this.value = val;
}
}
或者您可以添加我提供的第一个片段作为您在其他一些验证过程中调用的方法。 这由你决定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.