Pradeepb
Pradeepb

Reputation: 2562

shared v-model value between child and parent

I have a component which shares v-model same as parent component. The code is like below:

Vue.component('greeting', {
  template: '<input type="text" :name="name" v-on:input="updateSearch($event.target.value)"> ' ,
  props: ['name'],
  methods: {
    updateSearch: function(value) {
      this.$emit('input', value);
    }
  }
});


const app = new Vue({
  el: '#app',
  data: {
    name: ''
  }
});
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
  
  Child: <greeting v-model="name"></greeting>
  <br><br><br>
  Main: <input type="text" v-model="name" placeholder="" />

</div>

I want to update both input boxes if the user enters text in either of them. Any suggestions would be helpful.

Upvotes: 0

Views: 416

Answers (3)

Jishad
Jishad

Reputation: 163

I think, what you are looking for is .sync modifier for events in Vue.js 2.3.0+.

You can find a sample implementation of the same in my article here.

Upvotes: 0

Chris Li
Chris Li

Reputation: 2671

If you pass in a reference like an object as prop, you can bind a property of that object on both your parent and child

Vue.component('greeting', {
  template: '<input type="text" v-model="name.value" />' ,
  props: ['name']
});


const app = new Vue({
  el: '#app',
  data: {
    name: { value: '' }
  }
});
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
  
  Child: <greeting v-bind:name="name"></greeting>
  <br><br><br>
  Main: <input type="text" v-model="name.value" placeholder="" />

</div>

Upvotes: 1

Matheus Valenza
Matheus Valenza

Reputation: 919

Usually is a bad practice change props inside child component. In this case, you can create two different variables and update the other one when some of them changes it value (via events and props).

So, greeting component would $emit some event which you will catch inside main component and update main's name

On the other hand, main component would pass a prop to greeting which will be reactive considering changes inside main and will update variable name inside greeting's data.

If you get more cases like that, think about using vuex

Upvotes: 1

Related Questions