vue multiselect lost reactivity on updating v-model

1.9k views Asked by At

My Vue multiselect component:

<multiselect 
    required 
    label="role" 
    track-by="role" 
    :close-on-select="false"
    :clear-on-select="false" 
    :preserve-search="true" 
    :preselect-first="false"
    :multiple="true" 
    :options="roles" 
    v-model="role.roleID" 
>
    <template slot="selection" slot-scope="{ values, isOpen }">
        <span
            class="multiselect__single"
            v-if="values.role &amp;&amp; !isOpen"
        >
            {{ values.role }} 
        </span>
    </template>                
</multiselect>

And data method:

data: function () {
    return {
        role: {
            role: '',
            description: '',
            scopeLevel: '',
            roleID: ''
        },
        roles: [],
    }
},

And when I make an API call, I get the below response:

let responce = [
    {            
        'id': '1',
        'role': 'Test role'            
    }, {
        'id': '2',
        'role': 'Test role 2'  
    }
]

When I try to bind this response to multiselect v-model, i.e. role.roleID:

this.role.roleID = responce

The multiselect component loses reactivity.

Let me know what I am doing wrong here. Thanks.

2

There are 2 answers

3
IVO GELOV On

You have some mistakes:

  1. the role variable in your data section is initialized as Object - but it should be an Array or otherwise you can not select multiple options
  2. the v-model is bound to roleID - but your response does not have such a property
<multiselect v-model="role" />
data: () => ({
  roles: [], // the list of all options
  role: [], // the list of currently selected options
})
this.roles = response
0
Chathuranga K On

Without directly assigning the role, try using Vue setter.

this.$set(this.role, 'roleID', responce);