Tanmay
Tanmay

Reputation: 3159

VueJS sending v-model property from child to parent

Let's say I have a Vue component like this one:

 Vue.component('child-comp',{
    props:['name', 'val'],
    data: function(){
       return {
           picked: ''
       }
    },
    template: '<div><input type="radio" :name="name" :value="val" v-model="picked"><slot></slot></div>'
});

And The Parent vue instance:

new Vue({
  el: '#app',
  data: {
    message: 'Hello'
  }
});

And in the HTML:

<div id="app">
  <child-comp name="fruits" val="apple">Apple</child-comp>
  <child-comp name="fruits" val="banana">Banana</child-comp>
  <child-comp name="fruits" val="cherry">Cherry</child-comp>
  <p>{{ picked }}</p> <!-- this throws an error -->
</div>

How can I pass the v-model property picked from the child component to the root instance. Only way I know of is $emitting an event from the child component and later capturing the passed data in root instance. But as you can see, to access a simple property, triggering an event is overkill. How can I access {{ picked }} within <p>{{ picked }}</p>

Upvotes: 3

Views: 4097

Answers (2)

Andrei Roba
Andrei Roba

Reputation: 2322

If your child-comp is an input component you could use two-way props. These work similar to v-model but you can use them with your custom components.

<custom-input
  :value="something"
  @input="value => { something = value }">
</custom-input>

You can find out more about this here and there. See this thread also. Good luck!

Upvotes: 2

Julia
Julia

Reputation: 95

That's easy:

new Vue({
  el: '#app',
  data: {
    message: 'Hello',
   picked: 'apple'
  }
});

And in child :

Vue.component('child-comp',{
    props:['name'],
    template: '<div><input type="radio" :name="name" v-model="picked"><slot></slot></div>'
});

Upvotes: -1

Related Questions