0π
I understand your concern. These questions are not very well answered in the Vue community. If you are coming from React, there is, of course, some learning curve but you get to know all the best practices first hand.
In React, in this case Vue, In my component A
, I will have state(data) for both the input in B
and C
. Then in my template I would do somethign like this.
<div>
<A :value="aValue" onChange="(value) => aValue = value"/>
<B :value="bValue" onChange="(value) => bValue = value"/>
<input type="button" value="submit" @click="myFucntion"/>
</div>
So now you have all the data in the top level(container) component. This will allow most of our component to be stateless and reusable. I understand this is a little verbose, but I think it is worth it.
0π
You can use Event driven approach. this will be more elegant way to pass data from child to parent
.
Vue.component('child', {
template: '#child',
//The child has a prop named 'value'. v-model will automatically bind to this prop
props: ['value'],
data: function() {
return {
internalValue: ''
}
},
watch: {
'internalValue': function() {
// When the internal value changes, we $emit an event. Because this event is
// named 'input', v-model will automatically update the parent value
this.$emit('input', this.internalValue);
}
},
created: function() {
// We initially sync the internalValue with the value passed in by the parent
this.internalValue = this.value;
}
});
new Vue({
el: '#app',
data: {
inputs: {
value1: 'hello1',
value2: 'hello2'
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
<div id="app">
<p>Parent value: {{inputs}}</p>
<child v-model="inputs.value1"></child>
<child v-model="inputs.value2"></child>
</div>
<template id="child">
<input type="text" v-model="internalValue">
</template>
reference taken from here : vuejs update parent data from child component
author :
- [Vuejs]-Add a callback to a Vue instance's destroy hook
- [Vuejs]-How to list all available slots in vue component