我是vue新手,在option元素中的条件渲染(v-if)方面有问题。当我有一个空的数组时,我想显示一个禁用的选项,否则它会显示国家。就像这个描述中的https://vuejs.org/v2/guide/conditional.html一样,但不幸的是,这不适用于option HTML元素。我错过了什么?
new Vue({
el: '#app',
data: {
selected: '',
optionAvailable: true,
countries: [
//{ name: 'USA', population: '300M' },
//{ name: 'Canada', population: '100M' },
//{ name: 'Germany', population: '80M' },
]
},
created() {
if(!this.countries.length > 0) {
return this.optionAvailable = false;
}
return true;
},
methods: {
onChange(event) {
this.selected = event.value;
}
}
})
html:
<div id="app">
<select @change="onChange($event.target)">
<option v-if="optionAvailable" v-for="(country,index) in countries" :value="country.population">{{ country.name }}</option>
<option v-else disabled>-</option>
</select>
<br>
<span>{{ selected }}</span>
</div>
这里是jsfiddle:
发布于 2018-07-03 05:56:04
试试这个:
模板
<div id="app">
<select @change="onChange($event.target)">
<option v-if="countries.length" v-for="(country,index) in countries" :value="country.population">{{ country.name}}</option>
<option v-else>----</option>
</select>
<span>{{ selected }}</span>
</div>
脚本
new Vue({
el: '#app',
data: {
selected: '',
optionAvailable: true,
countries: [
{ name: 'USA', population: '300M' },
{ name: 'Canada', population: '100M' },
{ name: 'Germany', population: '80M' } ]
},
methods: {
onChange(event) {
this.selected = event.value;
}
}
})
您不需要创建的钩子。您可以告诉v-if
直接查看countries
的长度。
发布于 2018-07-03 14:35:14
试用此模板
<div id="app">
<select @change="onChange($event.target)" :disabled="!countries.length">
<option v-if="!countries.length" value="">No available countries</option>
<option v-for="(country,index) in countries" :value="country.population">{{ country.name }}</option>
</select>
<br>
<span>{{ selected }}</span>
</div>
脚本
new Vue({
el: '#app',
data: {
selected: '',
countries: []
},
methods: {
onChange(event) {
this.selected = event.value;
}
}
})
https://stackoverflow.com/questions/51143402
复制相似问题