我有一个经典的<Select>
输入,我想获取所选元素的文本。我能够得到价值,但不是文本:
<select v-model="ageCategory" class="form-control" @change="calculateCategoryName">
<option value="0">{{trans('core.no_age')}}</option>
<option value="1">{{trans('core.children')}}</option>
<option value="2">{{trans('core.teenagers')}}</option>
<option value="3">{{trans('core.adults')}}</option>
<option value="4">{{trans('core.masters')}}</option>
<option value="5">{{trans('core.custom')}}</option>
</select>
我可以通过以下方式获得价值:
var ageCategory = this.ageCategory;
但是我无法获得文字......任何想法我应该怎么做?
答案 0 :(得分:2)
客户端呈现的选择选项
由于您的值恰好是从零开始的数字(0到5),您可以将翻译键保留在组件中的数组中:
JS:
data: {
ageCategory: 0,
ageValues: [
'core.no_age',
'core.children',
'core.teenagers',
'core.adults',
'core.masters',
'core.custom'
],
},
methods: {
calculateCategoryName: function(event) {
var ageCategory = this.ageCategory;
var ageCategoryName = this.ageValues[this.ageCategory];
}
}
然后,您可以使用v-for
loop:
<select v-model="ageCategory" class="form-control" @change="calculateCategoryName">
<option v-for="ageValue in ageValues" :value="$index">{{ trans(ageValue) }}</option>
</select>
服务器端呈现选择选项
如果您需要从实际选择选项中获取值,您可以通过DOM using v-el
获取它:
methods: {
calculateCategoryName: function() {
var ageCategory = this.ageCategory;
var $ageCategorySelect = this.$els.ageCategory;
var ageCategoryOption = $ageCategorySelect.options[$ageCategorySelect.selectedIndex];
var ageCategoryName = ageCategoryOption.text;
}
}
HTML:
<select v-model="ageCategory" class="form-control" @change="calculateCategoryName" v-el:age-category>
<option value="0">{{trans('core.no_age')}}</option>
<option value="1">{{trans('core.children')}}</option>
<option value="2">{{trans('core.teenagers')}}</option>
<option value="3">{{trans('core.adults')}}</option>
<option value="4">{{trans('core.masters')}}</option>
<option value="5">{{trans('core.custom')}}</option>
</select>