我想在网页上创建一个按钮,该按钮将在某个值后开始有“2”的步长。
我目前使用的 JS 框架是 vue.js,这是我目前拥有的框架:
<input :step="something >= 5 ? 2 : 1" type="number" >
the : before step 是 vue.js 中 v-bind 的简写。 现在我的问题是,一旦我的值为 5,当我希望用户能够选择 4 而不必通过值 3 然后 4 时,降级也将是 2。
或者我想我可以生成一个数字数组,但我不知道如何在这个过程中引入一个步骤 2。
像这样 [1, 2, 3, 4, 5, 7, 9, 11, 13...]
最佳答案
您可以通过编程方式执行此操作。
已更新以使用 watch 并管理“编辑”模式,以便我们在键入时更改值。
<template>
<div id="app">
<input :step="1" type="number" v-model="something" @keydown="keydown" />
{{ editing }}
</div>
</template>
<script>
export default {
name: "App",
data: function() {
return {
something: 0,
last: 0,
editing: false
};
},
methods: {
keydown(e) {
this.editing = e.key !== "Enter";
if (!this.editing) {
this.validateSomething(Number(this.something));
}
},
validateSomething(v) {
if (v > 5) {
if (v % 2 === 0) {
if (v > this.last) {
this.something = v + 1;
} else {
this.something = v - 1;
}
}
}
this.last = this.something;
}
},
watch: {
something: function(newVal, oldVal) {
console.log(newVal, oldVal);
let v = Number(newVal);
if (!this.editing) {
this.validateSomething(v);
}
}
}
};
</script>
这是一个工作代码和框:https://codesandbox.io/s/mm6x3q60px
关于javascript - 如何让按钮在某个点后改变它的步骤而不丢失值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53560470/