How can i send the country key through the event and get the corresponding country selected.
right now it just gets overwritten to a string.
<template>
<div>
<multiselect
:selected.sync="selected"
:options="options"
@update="updateSelected"
:searchable="true",
:close-on-select="true",
:allow-empty="false",
deselect-label="Can't remove this value"
key="key"
label="label"
placeholder="Select Country">
</multiselect>
</div>
</template>
<script>
import Multiselect from 'vue-multiselect'
export default {
components: { Multiselect },
data () {
return {
selected: null,
options: countries
}
},
methods: {
updateSelected (newSelected) {
this.selected = newSelected
// console.log(this.key);
}
},
events: {
'changeSelected': function (selected) {
this.selected = selected;
}
}
}
let countries = [
{'key' : 'AF', 'label' : 'Afghanistan'},
{'key' : 'AX', 'label' : 'Aland Islands'},
{'key' : 'AL', 'label' : 'Albania'},
{'key' : 'DZ', 'label' : 'Algeria'},
{'key' : 'AS', 'label' : 'American Samoa'},
{'key' : 'AD', 'label' : 'Andorra'},
...
That's because two-way binding is deprecated since 1.0 release. You need to
handle updating the selected value with the
@update="updateSelectedHandler"
event handler. Please look into the docs for details.
Thanks for answering ,but how to can i change the selected option from the parent sending the country key.
Parent
methods:{
populateAddressFields(){
this.$broadcast('changeSelected', this.countryKey);
}
}
Multiselect
events: {
'changeSelected': function (countryKey) {
???
}
}
I guess you need to set the whole object not just the key. This is because the :selected prop expects an object it would find inside the :options prop. If there is no way to broadcast the whole object to the child, try using the find array method.
events: {
'changeSelected' (countryKey) {
this.selected = this.options.find(country => country.key === countryKey)
}
}
Also if this is just a wrapper component, what about passing the selected value and countries as props and skipping the $broadcast? In Vue 2.0 $broadcast it is already deprecated as it is considered a bad design.
I guess one of the reasons for this is that you have to be very careful not to use the changeSelected event in any of the parent components.
Thank you, worked perfectly.
Happy to help! :)
Most helpful comment
I guess you need to set the whole object not just the key. This is because the
:selectedprop expects an object it would find inside the:optionsprop. If there is no way to broadcast the whole object to the child, try using thefindarray method.Also if this is just a wrapper component, what about passing the selected value and countries as props and skipping the
$broadcast? In Vue 2.0$broadcastit is already deprecated as it is considered a bad design.I guess one of the reasons for this is that you have to be very careful not to use the
changeSelectedevent in any of the parent components.