Reputation: 7052
Is it possible to pass v-model value to another component ? I have HTML code is like below
<div id='example-3'>
<input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
<label for="jack">Jack</label>
<input type="checkbox" id="john" value="John" v-model="checkedNames">
<label for="john">John</label>
<input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
<label for="mike">Mike</label>
</div>
vue.js code is like below
data: {
checkedNames: []
}
I can use this v-model value in same component using below code.
<span>Checked names: {{ checkedNames }}</span>
But how can I use v-model value in another component ?
Upvotes: 0
Views: 1356
Reputation:
You can emit events with the v-model value each time one of the checkboxes is ticked:
<input type="checkbox" id="mike" value="Mike" v-model="checkedNames" @change="onChange">
<label for="mike">Mike</label>
methods: {
onChange () {
this.$root.$emit('checkbox.changed', this.checkedNames)
}
}
Listen for the event in another component:
// my-component.js
created () {
this.$root.$on('checkbox-changed', payload => {
// do something with payload...
}
}
In the context of components, you should always be declaring the data
property as a function, too.
data () {
return {}
}
Your other option is using a state management strategy, i.e. Vuex, or similar.
Upvotes: 1