How to create a custom component and communicate with the parent through `v-model` in Vue.js
Right now I have lines of code to make a select box which looks like this
<select v-model="somethingSomething">
<option disabled selected>Select me</option>
<option v-for="..." :value="..." :key="...">...</option>
</select>
However, I have this on many pages and it would be tedious to repeat myself.
So I went with creating a custom component and use that in every page I need. It looks like this
<template>
<select @input="handleInput">
<option v-for="item in collection" :key="item.id">...</option>
</select>
</template><script>
export default {
name: 'OptionSelectComponent',
data() {
return {
collection: [...],
}
},
methods: {
handleInput(e) {
this.$emit('input', e.target.value)
}
},
mounted() {
this.gettAllIconSizes();
}
}
</script>
On the page you want to use, use
<OptionSelectComponentv-model="somethingSomething"></OptionSelectComponent>
and don’t forget to import
import OptionSelectComponent from '@/components/OptionSelectComponent.vue'
and export the component
export default {
components: {
OptionSelectComponent,
},
...
}
Annnnd… Bob’s your uncle!
Explanation
Since it’s <select></select>
, we have to check using @input
which fires when an <option></option>
is selected.
We handle the event using handleInput(e)
with e
(stands for event) as its argument. Then we emit the event along with e.target.value
(how I got this? well, just console.log(e)
and see which one is the one you you — it’s stupid and it works duh)
And that’s it. You can modify the code to get the result you want.
Reference
- Add `v-model` Support to Custom Vue.js Component by Samuel Oloruntoba retrieved from https://scotch.io/tutorials/add-v-model-support-to-custom-vuejs-component