Search code examples
javascriptvue.jsvuexvue-multiselect

Vue-Multiselect and Vuex: Having a value from store pre-selected


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.


Solution

  • If you working with Vuex the best way to manipulate data in storage use state,
    mutations, actions and getters to get any type of data. For more information check this post