简体   繁体   English

vue.js - 如何绑定只读输入字段? v-bind:value 还是 v-model?

[英]vue.js - how to bind read only input fields? v-bind:value or v-model?

I am trying to implement a simple vue.js applicaton and I ran into this conceptual question: I have a small set of read only input fields showing values for calculated fields.我正在尝试实现一个简单的 vue.js 应用程序,但遇到了这个概念性问题:我有一小组只读输入字段,显示计算字段的值。 I have tried both approaches and I am slightly leaning towards the v-bind approach (v-model is mostly for inputs), but I am really curious about the consequences of using one or the other.我已经尝试了这两种方法,并且我稍微倾向于 v-bind 方法(v-model 主要用于输入),但我真的很好奇使用其中一种方法的后果。

<input id="cp-remaining" type="number" min="50" max="80" size="2" readonly="true" v-bind:value="characterPointsRemaining">
<input id="cp-remaining" type="number" min="50" max="80" size="2" readonly="true" v-model.number="characterPointsRemaining">

From Vue.js guide:来自 Vue.js 指南:

Remember:记住:

 <input v-model="something">

is just syntactic sugar for:只是语法糖:

 <input v-bind:value="something" v-on:input="something = $event.target.value">

So using v-model for input, that cannot be changed is pointless, as it will never generate input event.因此,使用 v-model 进行输入,无法更改是没有意义的,因为它永远不会生成输入事件。

Besides, as David L already pointed out, you probably should use something more proper for this use case, like <div> .此外,正如 David L 已经指出的那样,您可能应该为这个用例使用更合适的东西,比如<div>

As mentioned by Staszek, v-bind:value is the incomplete longhand for the v-model syntactic sugar.正如 Staszek 所提到的, v-bind:valuev-model语法糖的不完整的速记。

However, in your case, you should use neither.但是,在您的情况下,您都不应该使用。

Inputs are used to convey a very specific set of functionality to the user;输入用于向用户传达一组非常具体的功能; that they can interact with the form to provide their input .他们可以与表单交互以提供他们的输入 In this case, they cannot, because you've made the form readonly.在这种情况下,他们不能,因为您已将表单设置为只读。 However, a readonly input isn't necessarily any better because it implies to the user that you can actually do something to enable the input, which in your case isn't true.但是,只读输入不一定更好,因为它向用户暗示您实际上可以做一些事情来启用输入,在您的情况下这不是真的。

The most correct way to handle this scenario is to not use an input at all, but to use another element that more properly represents outputted data, binding the data via text interpolation :处理这种情况的最正确方法是根本不使用输入,而是使用另一个更恰当地表示输出数据的元素,通过文本插值绑定数据:

<div id="cp-remaining">{{characterPointsRemaining}}</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM