Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use :value and v-model on the same element in Vue.js

Tags:

vue.js

I would like to update some input fields

so I created an input element:

new Vue({
  el: '#app',
  data: {
    record: {
      email: '[email protected]'
    },
    editing: {
      form: {}
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="text" :value="record.email" v-model="editing.form.email">
  <pre>{{ editing.form.email }}</pre>
</div>

In this input element I added :value attr and a v-model

Unfortunately I get an error:

conflicts with v-model on the same element because the latter already expands to a value binding internally

What is the best solution to fill the input field with data and then update it?

I also tried to add :name="..." instead of :value="..."

http://jsfiddle.net/to9xwL75/

like image 989
Greg Ostry Avatar asked Dec 12 '18 08:12

Greg Ostry


People also ask

Can I use v-model on a component?

Using v-model on a custom component allows us to do both of these stops with one directive. value acts as our source of truth. We bind it to our child component to set the value of our input, and when our input changes - we update with value = $event - which sets value to the new value of our input.

Does Vue JS have two way data binding?

Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. The v-model directive makes two-way binding between a form input and app state very easy to implement.

What is the difference between v-model and value?

In simple words v-model is for two way bindings means: if you change input value, the bound data will be changed and vice versa. but v-bind:value is called one way binding that means: you can change input value by changing bound data but you can't change bound data by changing input value through the element.

How do I get my element value at Vue?

To get an input value in Vue, we can use the v-model directive to set up a two-way binding between the value and a variable. Every time the user changes the text in the input field, the text variable will be updated automatically. We can then use this variable to perform an action or display information.


1 Answers

Don't use :value with v-model together.

Use mounted() to update your model and pre-fill input value:

data() {
  return {
    record: {
      email: ''
    }
  }
},
mounted() {
  setTimeout(() => {
    this.record.email = '[email protected]'
  }, 500)
}
like image 173
Alexander Kim Avatar answered Oct 13 '22 11:10

Alexander Kim