Vue使用现有值形成输入绑定 [英] Vue form input bindings with existing value
问题描述
我想用模型绑定输入。页面加载时,输入有一个值。但是当我与模型绑定时,它会变空,因为我使用null或空值初始化模型。
I want to bind an input with a model. When the page loads, the input has a value. But when I bind with a model, it gets empty as I initialize the model with a null or empty value.
<div id="update-email">
<input type="text" name="email" value="me@example.com" v-model="email">
{{ email }}
</div>
JavaScript:
JavaScript:
new Vue({
el: '#update-email',
data() {
return {
email: '',
};
}
});
jsfiddle: https://jsfiddle.net/Debiprasad/v8wyj2kw/
jsfiddle: https://jsfiddle.net/Debiprasad/v8wyj2kw/
如何更新电子邮件
加载时输入值的值?
How can I update email
value with the value of the input when it loads?
推荐答案
我通过将模型值初始化为输入字段的值。这种方式当vue最初将输入字段设置为模型值时,它就是输入字段中的值。
I handle this by initializing my model value to the value of the input field. This way when the vue initially sets the input field the model value, it's the value that was in the input field.
下面的示例使用jquery:
Example below using jquery:
<div id="update-email">
<input id="email" type="text" name="email" value="me@example.com" v-model="email">
{{ email }}
</div>
Javasacript:
Javasacript:
new Vue({
el: '#update-email',
data() {
return {
email: $('#email').val(),
};
}
});
如果你想在没有jquery的情况下这样做,只需更改 $('#电子邮件')。val()
到 document.getElementById('email')。value
If you want to do it without jquery, just change $('#email').val()
to document.getElementById('email').value
这篇关于Vue使用现有值形成输入绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!