Reputation: 6153
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="[email protected]" v-model="email">
{{ email }}
</div>
JavaScript:
new Vue({
el: '#update-email',
data() {
return {
email: '',
};
}
});
jsfiddle: https://jsfiddle.net/Debiprasad/v8wyj2kw/
How can I update email
value with the value of the input when it loads?
Upvotes: 7
Views: 8993
Reputation: 65
Ron's response and yuriy636's comment are perfectly answering your question. Only to complement with a more advanced solution using Vuex (https://vuex.vuejs.org/en/):
const store = new Vuex.Store({
state: {
email: '[email protected]'
}
})
new Vue({
el: '#update-email',
store,
created() {
this.email = this.$store.state.email
},
data() {
return {
email: '',
};
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.4.0/vuex.min.js"></script>
<div id="update-email">
<input type="text" name="email" v-model="email"> {{ email }}
</div>
Upvotes: 0
Reputation: 43881
You can use a directive to put the value into the element and issue an input event.
new Vue({
el: '#update-email',
data: {
email: null
},
directives: {
init: {
bind(el) {
el.value = el.getAttribute('value');
el.dispatchEvent(new Event('input'));
}
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="update-email">
<input v-init type="text" name="email" value="[email protected]" v-model="email"> {{ email }}
</div>
Upvotes: 3
Reputation: 12222
To add a non-JQuery variant of Ron C's answer, and to make explicit the answer suggested by the link yuriy linked to, here's the solution suggested by the creator of Vue.js:
https://jsfiddle.net/vzns7us7/
Template:
<script>
// rendered by server
window.__FORM__ = {
fill: 'my_default_value'
}
</script>
<div id="test">
<input type="text" v-model="fill">
{{ fill }}
</div>
JavaScript:
new Vue({
el: '#test',
data () {
return window.__FORM__ || {
fill: 'none'
}
}
});
Upvotes: 0
Reputation: 33771
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.
Example below using jquery:
<div id="update-email">
<input id="email" type="text" name="email" value="[email protected]" v-model="email">
{{ email }}
</div>
Javasacript:
new Vue({
el: '#update-email',
data() {
return {
email: $('#email').val(),
};
}
});
If you want to do it without jquery, just change $('#email').val()
to document.getElementById('email').value
Upvotes: 5