How can i bind input to object in vue.js

4k views Asked by At

Is there a way to bind input to objects instead of single variables.

I know we can do this simple trick

<input v-model="name">

But the following doesn't work:

<input v-model="user.name">

That's what i was used to in Angular, is there a way to achieve this in vue.js?

2

There are 2 answers

0
sept08 On BEST ANSWER

you can bind directly to data, code as follow:

var demo = new Vue({
    el: "#demo",
    data: {
      user: {
        name: "please enter"
      }
    }
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<div id="demo">
  <input v-model="user.name">
  <span>{{user.name}}</span>
</div>

0
Saurabh On

This works in Vue as well, make sure to define complete object in data which will make it reactive, Here is a working fiddle.

Vue Code:

var demo = new Vue({
    el: '#demo',
    data: function(){
        return {
        user: {
            name: 'This is working fine'
        }
      };
    }
})