Reputation: 582
imagine a Vuejs-Application with Vuex. I want to have a mulitselect-dropdown. Basic example in the Vue-component:
<template>
<div>
<multiselect
v-model="values"
:options="options">
</multiselect>
</div>
</template>
<script>
import Multiselect from 'vue-multiselect'
export default {
components: { Multiselect },
data () {
return {
values: null,
options: ['bar', 'foo', 'hello','test']
}
}
}
</script>
<style src="vue-multiselect/dist/vue-multiselect.min.css"></style>
Now, if I initialize "values" in data like this:
values: ["test"]
The multiselect-dropdown has "test" as already selected option. I can also deselect it on click and select it again, since it is in options.
If I try to initialize my values like this:
values:[this.$store.state.variableIwantPreselected]
it does not fully work. In the selection-area/dropdown search field, those green boxes with the selected item's name are normally displayed. For me, it does not display the string in the green box, which is in this.$store.state.variableIwantPreselected, but only a small green box with nothing written in it.
I think I missed something about Vuex and lifecycle hooks, but I could not figure out what.
Upvotes: 2
Views: 2106
Reputation: 582
A further note for people running into similar problems: check, when your component is rendered/loaded. In my case, it was loaded before the value in the store was changed (tends to happen when you use vue-router and have several components displaying with only one route).
Solution: take a deeper look into the updated lifecycle hook.
I now call a function in the updated lifecycle hook. The function is declared in methods. The function checks, if my values (now initialized as empty list) has a length of 0. If so, the store value is pushed to the list.
in data:
values: []
in methods:
checkValues (){
if(this.values.length === 0){
this.values.push(this.$store.state.variableIwantPreselected)
}
}
in updated():
this.checkValues()
Upvotes: 1