Reputation: 2292
I am using vue multiselect and I need my options to come from an api. When I use the example from the official docs it works.
import Multiselect from 'vue-multiselect'
export default {
components: {
Multiselect
},
data () {
return {
value: [
{ name: 'Vue.js', language: 'JavaScript' }
],
options: [
{ name: 'Vue.js', language: 'JavaScript' },
{ name: 'Adonis', language: 'JavaScript' },
{ name: 'Rails', language: 'Ruby' },
{ name: 'Sinatra', language: 'Ruby' },
{ name: 'Laravel', language: 'PHP' },
{ name: 'Phoenix', language: 'Elixir' }
]
}
}
}
But if I replace the options with my data it fails
data: function () {
return {
value: [],
options: this.users
}
},
methods: {
getUsers: function () {
this.$http.get('/api/get/users').then(function (response) {
this.users = response.data;
this.updateUsers();
console.log(this.users)
}, function (response) {
console.log(response)
});
},
updateUsers: function () {
this.options = this.users;
}
},
created: function () {
this.getUsers();
}
};
I have tried calling the method with mounted
, beforeMount
and beforeCreate
and none of them work. My console shows the following errors:
I am sure the issue is with how am passing the options but I don't know how to pass them the right way.
For the template I am just using the default for now:
<div>
<label class="typo__label">Simple select / dropdown</label>
<multiselect v-model="value" :options="options" :multiple="true" :close-on-select="false" :clear-on-select="false" :hide-selected="true" placeholder="Pick some" label="name" track-by="name"></multiselect>
<pre class="language-json"><code>{{ value }}</code></pre>
</div>
Upvotes: 2
Views: 7911
Reputation: 4895
In console it's saying prop 'options' expected array got undefined
mean value to this.options
not assigning.
Try like this :
create variable outside this.$http request.
let self = this;
then replace :
this.options
to self.options
This should work.
Upvotes: 0
Reputation: 73619
Try initializing options as an empty array: []
data: function () {
return {
value: [],
options: []
}
},
Later when you get the data from backend, you can populate the data in options, as follows:
methods: {
getUsers: function () {
this.$http.get('/api/get/users').then( response => {
this.options = response.data;
console.log(this.users)
}, function (response) {
console.log(response)
});
},
Upvotes: 5