在Vue.js中创建动态的两个关联下拉菜单,可以通过以下步骤实现:
categories
表示第一个下拉菜单的选项,另一个数组subcategories
表示第二个下拉菜单的选项。data() {
return {
categories: ['Category 1', 'Category 2', 'Category 3'],
subcategories: {
'Category 1': ['Subcategory 1.1', 'Subcategory 1.2', 'Subcategory 1.3'],
'Category 2': ['Subcategory 2.1', 'Subcategory 2.2', 'Subcategory 2.3'],
'Category 3': ['Subcategory 3.1', 'Subcategory 3.2', 'Subcategory 3.3']
},
selectedCategory: '',
selectedSubcategory: ''
}
}
v-model
指令绑定选中的值,并使用v-for
指令循环渲染下拉菜单的选项。<template>
<div>
<select v-model="selectedCategory" @change="updateSubcategories">
<option value="">Select Category</option>
<option v-for="category in categories" :value="category">{{ category }}</option>
</select>
<select v-model="selectedSubcategory">
<option value="">Select Subcategory</option>
<option v-for="subcategory in subcategories[selectedCategory]" :value="subcategory">{{ subcategory }}</option>
</select>
</div>
</template>
updateSubcategories
来更新第二个下拉菜单的选项,根据第一个下拉菜单的选中值。methods: {
updateSubcategories() {
this.selectedSubcategory = '';
}
}
<template>
<div>
<select v-model="selectedCategory" @change="updateSubcategories">
<option value="">Select Category</option>
<option v-for="category in categories" :value="category">{{ category }}</option>
</select>
<select v-model="selectedSubcategory">
<option value="">Select Subcategory</option>
<option v-for="subcategory in subcategories[selectedCategory]" :value="subcategory">{{ subcategory }}</option>
</select>
</div>
</template>
<script>
export default {
data() {
return {
categories: ['Category 1', 'Category 2', 'Category 3'],
subcategories: {
'Category 1': ['Subcategory 1.1', 'Subcategory 1.2', 'Subcategory 1.3'],
'Category 2': ['Subcategory 2.1', 'Subcategory 2.2', 'Subcategory 2.3'],
'Category 3': ['Subcategory 3.1', 'Subcategory 3.2', 'Subcategory 3.3']
},
selectedCategory: '',
selectedSubcategory: ''
}
},
methods: {
updateSubcategories() {
this.selectedSubcategory = '';
}
}
}
</script>
这样,当你选择第一个下拉菜单的选项时,第二个下拉菜单的选项会根据选择的值进行动态更新。
领取专属 10元无门槛券
手把手带您无忧上云