Before anything else, I'm using Vuetify's VSwitch
component inside my-component
. I want to return the value of my-component
to the parent.
something like <my-component v-model="returnedData"></my-component>
Then the inside <my-component></my-component>
<template>
<div>
<v-switch v-model="toggledData" value="John"></v-switch>
<v-switch v-model="toggledData" value="Andrew"></v-switch>
<v-switch v-model="toggledData" value="Melissa"></v-switch>
<v-switch v-model="toggledData" value="Elizabeth"></v-switch>
</div>
</template>
<script>
export default {
props: ['value'],
data () {
return {
toggledData: []
}
}
}
</script>
I want to return the value of toggledData
to the parent that's using it if possible. I've been browsing the net for a while and I've been seeing only with inputs. But it was possible to some of Vuetify's components like the VTreeview
so I was thinking maybe it's possible.
The parent component listens to the child's changes with the childToParent
and if there is any change I call the childChanged ()
method
// Parent Component
<template>
<div id="parent">
<p>{{parentToggledData}}</p>
<Child v-on:childToParent="childChanged"/>
</div>
</template>
<script>
import Child from "./Child";
export default {
name: "parent",
components: {
Child
},
data() {
return {
parentToggledData: []
};
},
methods: {
childChanged(value) {
this.parentToggledData = value;
}
}
};
</script>
I listen to the changes on each v-switch
, and if there is one, I call the emitToParent ()
method in this method, I send the changes to the parent with $emit
which takes as parameter the event listened by the parent childToParent
and "the value to send this.toggledData
// Child Component
<template>
<div id="child">
<v-switch v-model="toggledData" value="John" @change="emitToParent"></v-switch>
<v-switch v-model="toggledData" value="Andrew" @change="emitToParent"></v-switch>
<v-switch v-model="toggledData" value="Melissa" @change="emitToParent"></v-switch>
<v-switch v-model="toggledData" value="Elizabeth" @change="emitToParent"></v-switch>
</div>
</template>
<script>
export default {
name: "child",
data() {
return {
toggledData: []
};
},
methods: {
emitToParent(event) {
console.log(event)
console.log(this.toggledData)
this.$emit("childToParent", this.toggledData);
}
}
};
</script>