Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue form input bindings with existing value

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?

like image 718
Debiprasad Avatar asked Sep 16 '17 13:09

Debiprasad


2 Answers

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

like image 170
RonC Avatar answered Oct 19 '22 10:10

RonC


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>
like image 3
Roy J Avatar answered Oct 19 '22 10:10

Roy J