Vuetify 2:使 v-text-field 仅在失去焦点时更新其模型

huangapple go评论67阅读模式
英文:

Vuetify 2: make a v-text-field update its model only on loss of focus

问题

我正在使用 Vuetify 2 中的 v-text-field。我希望它仅在组件失去焦点时更新其模型(而不是在每次按键后更新模型)。我之所以这样做是因为它是一个格式化为两位小数的数字。我希望在用户导航离开后将 "12" 转变为 "12.00",但在用户输入时不要这样做,因为用户可能在小数点之前输入额外的数字。谢谢。

英文:

I'm using a v-text-field in Vuetify 2. I want it to update its model only when the component loses focus (as opposed to updating the model after every keypress). I want this because it's a number which is formatted to two decimal places. I want "12" to become "12.00" after the user navigates away, but not while the user is typing, because the user may type additional digits before the decimal point. Thank you.

答案1

得分: 1

你需要将 v-model 更改为其展开形式,使用 v-bind:valuev-on:input 两者。不要使用在每次用户输入时触发的 input 事件,而是使用在以下条件下触发的change事件

元素在失去焦点后其值发生变化时触发:适用于用户交互是输入而不是选择的元素,例如 <textarea><input> 元素的 textsearchurltelemailpassword 类型。

原生的 <input> 元素会将元素的值存储在 $event.target.value 中,但在 Vuetify 的 <v-text-field> 中,值只存储在 $event 中,所以你可以像这样设置你的 v-text-field:

<v-text-field
  type="number"
  :value="text"
  @change="text = $event"
></v-text-field>
<script>
export default {
  data() {
    return {
     text: ''
    }
  }
}
</script>

codepen示例

英文:

You'll need to change the v-model to it's expanded form that uses both v-bind:value and v-on:input. Instead of using the input event which fires on every user input, you'll want to use the change event which fires under the following condition:

> When the element loses focus after its value was changed: for elements where the user's interaction is typing rather than selection, such as a <textarea> or the text, search, url, tel, email, or password types of the <input> element.

Native <input> element would give you the element's value on $event.target.value, but with Vuetify's <v-text-field> the value is just on $event so you can set up your v-text-field like this:

<v-text-field
  type="number"
  :value="text"
  @change="text = $event"
></v-text-field>
<script>
export default {
  data() {
    return {
     text: ''
    }
  }
}
</script>

codepen example

huangapple
  • 本文由 发表于 2023年6月15日 02:03:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定