Reputation: 13162
I have vue component like this :
<script>
export default{
template: '\
<select class="form-control" v-on:change="search">\
<option v-for="option in options" v-bind:value="option.id ? option.id+\'|\'+option.name : \'\'">{{ option.name }}</option>\
</select>',
mounted() {
this.fetchList();
},
...
};
</script>
It works. No error
But, I want to add condition again in select
If it meets the conditions then selected
I add condition like this :
template: '\
<select class="form-control" v-on:change="search">\
<option v-for="option in options" v-bind:value="option.id ? option.id+\'|\'+option.name : \'\'" option.id == 1 ? \'selected\' : \'\'>{{ option.name }}</option>\
</select>',
There exist error like this :
[Vue warn]: Property or method "option" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
How can I solve it?
Upvotes: 1
Views: 4306
Reputation: 14150
I would change to a v-model
based:
<select @change="search" v-model="select">
<option v-for="option in options" :value="option.id">
{{ option.name }}
</option>
</select>
<script>
export default {
props: {
value: [Number, String]
},
data() {
return { select: this.value };
},
watch: {
value: function (val) {
this.select = val;
}
},
methods: {
// ...
}
};
</script>
Upvotes: 4
Reputation: 2856
This should work. Change your code like this.
<option v-for="option in options" v-bind:value="option.id ? option.id+\'|\'+option.name : \'\'" v-bind:selected="option.id == 1">{{ option.name }}</option>\
Since selected
is boolean attribute you'll have to use v-bind:selected="<condition>"
. This will insert the attribute based on the conditional's result.
Upvotes: 4