Associating Vue Form Input with an Existing Value

I want to associate an input with a model. When the page loads, the input matters. But when I contact the model, it becomes 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:

 new Vue({ el: '#update-email', data() { return { email: '', }; } }); 

jsfiddle: https://jsfiddle.net/Debiprasad/v8wyj2kw/

How can I update the email value with the input value when loading it?

+5
source share
4 answers

I handle this by initializing the value of my model with the value of an input field. Thus, when vue initially sets the input field to the model value, this is the value that was in the input field.

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:

 new Vue({ el: '#update-email', data() { return { email: $('#email').val(), }; } }); 

If you want to do this without jquery, just change $('#email').val() to document.getElementById('email').value

+1
source

To add a non-jQuery Ron C answer option and give an explicit answer suggested by the yuriy link related here, 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' } } }); 
0
source

You can use the directive to put a value in an element and throw 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=" me@example.com " v-model="email"> {{ email }} </div> 
0
source

The answer to Ron and the comment by yuriy636 answer your question perfectly. Only to complement a more advanced solution using Vuex ( https://vuex.vuejs.org/en/ ):

 const store = new Vuex.Store({ state: { email: ' me@example.com ' } }) 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> 
0
source

Source: https://habr.com/ru/post/1271875/


All Articles