Technology Sharing

Vue cascading drop-down box selection thinking

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

In the original js thinking, the selection of cascading drop-down boxes is often to first bind the menu of the first-level drop-down box, then onchange in the drop-down box, get the current option in the onchange event, and then bind the data of the second-level drop-down box, and so on...

In the Vue framework, you should change your thinking. First, set the data of the first-level drop-down box, then watch the option. If it changes, set the data of the second-level drop-down box, and so on:

  1. <el-form-item label="省">
  2. <el-select v-model="where.provinceId" placeholder="请选择省份" clearable >
  3. <el-option v-for="item in provinces" :key="item.id" :label="item.name" :value="item.id" />
  4. </el-select>
  5. </el-form-item>
  6. <el-form-item label="市">
  7. <el-select v-model="where.cityId" placeholder="请选择市" clearable>
  8. <el-option v-for="item in cities" :key="item.id" :label="item.name" :value="item.id" />
  9. </el-select>
  10. </el-form-item>
  1. const provinces = ref([])
  2. const cities = ref([])
  3. onMounted(()=>{
  4. // 通过接口获取省份
  5. provinces.value = [...data]
  6. })
  7. watch: {
  8. provinceId: {
  9. deep: true,
  10. handler() {
  11. // 根据接口获取市的数据
  12. cities.value=[...data]
  13. // 清空城市的选择
  14. where.cityId=''
  15. }
  16. }
  17. },