I have it set up just like in the official example ... but the user's choice is stored in the DB, and the next time they go to the page I want it to be pre-set to their previous choice. I can't seem to figure out how to do it in this case, since the :options
is a computed property...
EDIT: I did not provide enough of my code... I updated it with more info... I did find the issue, it was two things (1) the data in prefs
was not in the same format as the data in paginated
, so it could not identify the initial value, and (2) I was not using v-model
but rather @input
because I need to send the choice to the database. By setting up v-model
to a dummy data variable and filling that variable with the data from prefs
in the same format as the options list, then it worked. I will post my answer also.
HTML
<v-select
:options="paginated"
:filterable="false"
@input="setValue"
@open="onOpen"
@close="onClose"
@search="(query) => (search = query)"
></v-select>
JS
...
props: ['prefs'],
...
data: function() {
...
countries: []
...
computed: {
filtered() {
return countries.filter((country) => country.includes(this.search))
},
paginated() {
return this.filtered.slice(0, this.limit)
},
hasNextPage() {
return this.paginated.length < this.filtered.length
},
},
...
methods: {
setValue: function(v) {
this.prefs = v.id;
(... ajax call to update database ...)
}
...
created: {
(... ajax call to populate this.countries from database ...)
}
CodePudding user response:
https://codepen.io/chauriya/pen/BaZOxby
Please look at the attached pen, Here I'm setting a default value to v-select with v-model, I see your prefs
is a prop, if you are passing default value to prefs
then it should set in v-select. If you are sending some default value in prop then please update your question it will be more clear than.
CodePudding user response:
My issue was twofold:
- I was not using
v-model
but rather@input
because I wanted to send the choice to the DB in an AJAX call, so there was nothing for the initial value to hook onto. - The data in
prefs
was not in the same format as the data inpaginated
(string vs. object) so it could not locate the initial selection in the options list.
Here I post the fixed code:
HTML
<v-select
:options="paginated"
:filterable="false"
v-model="dummy"
@input="setValue"
@open="onOpen"
@close="onClose"
@search="(query) => (search = query)"
></v-select>
JS
...
props: ['prefs'],
...
data: function() {
...
countries: [],
dummy: {}
...
computed: {
filtered() {
return countries.filter((country) => country.includes(this.search))
},
paginated() {
return this.filtered.slice(0, this.limit)
},
hasNextPage() {
return this.paginated.length < this.filtered.length
},
},
...
methods: {
setValue: function(v) {
this.prefs = v.id;
(... ajax call to update database ...)
}
...
created: {
let me = this;
(... ajax call to populate this.countries from database ...)
.then(function(resp) {
me.countries = resp.data;
me.dummy = me.countries.find(c => c.id == me.prefs);
})
}