v-model 在 Vue 2.x 中有哪些限制? [英] Which limitations v-model has in Vue 2.x?
问题描述
也许v-model
下面的问题有解决方案,但我没有看到相应的文档.
Maybe below problems of v-model
has solutions, but I have not see the appropriate documentation.
- 链接"v 模型:e.G.我们希望自定义组件具有
v-model
,而这个v-model
与子的元素的
相关v-model
. - 使用对象(包括数组,这是 ECMAScript 的
object
的特殊情况)作为v-model
. - 修改数据:e.G.用户只输入数字,但组件发出的值是逗号分隔的数字(例如,iser 的输入:4545667",发出的值:4,545,667")
- "Chaining" the v-model: e. g. we want custom component has the
v-model
, and thisv-model
is related with child<input>
's element'sv-model
. - Using the objects (including arrays which is the particular case of ECMAScript's
object
) asv-model
. - Modifying data: e. g. users inputs only digits, but the value which component emits is comma separated number (for the instance, iser's input: "4545667", emitted value: "4,545,667")
我研究的第一个问题:v-model 不能做什么?
The first question in my research: what v-model can not do?
推荐答案
v-model=formData"
=== v-bind:value=formData"v-on:input=formData = $event.target.value"
.它不是万能的魔法命令,而是编写基本功能的一种更短的方法.
v-model="formData"
=== v-bind:value="formData" v-on:input="formData = $event.target.value"
. It's not a magic command that does everything, but a shorter way to write a basic functionality.
要获得所需的行为,您必须编写自己的组件来获取该值并对其进行处理.
To get the behaviour you need, you have to write your own components that take the value and do something with it.
要在多层组件之间链接 v-model,您需要$emit
新数据,而不是更改组件状态的默认行为.最简单的方法是使用计算的getter/setter.我使用下面的代码将任何东西传递给从简单值到整个对象,再到处理与不同 html 输入绑定的自定义输入组件.
To chain v-model between multiple layers of components, you want to $emit
the new data rather than the default behaviour of changing the components' state. The easiest way to do this is by using a computed getter/setter. I use the code below to pass through anything from simple values to entire objects to custom input components that handle the binding to different html inputs.
--- ParentTemplate:
<Child v-model="formData"></Child>
-- ChildTemplate:
<input v-model="localValue">
-- ChildScript:
computed: {
localValue: {
get() {
return this.value;
},
set(localValue) {
this.$emit('input', localValue);
},
},
},
如果您需要在发送之前从输入中转换数据(例如格式化),您可以在 setter 中 $emit 之前使用计算值或方法来转换数据.
If you need to convert data from an input before it's sent out (eg formatting), you can use a computed value or method to transform the data before you $emit it in the setter.
这篇关于v-model 在 Vue 2.x 中有哪些限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!