uni-app 请问有类似城市多级联动的组件吗?

uni-app 请问有类似城市多级联动的组件吗?

9 回复

你找到相关的组件了么

更多关于uni-app 请问有类似城市多级联动的组件吗?的实战教程也可以访问 https://www.itying.com/category-93-b0.html


暂时没有,插件市场的不符合我的需求,我先放着在开发其他页面,等有空了再自己改改他们的~

我也类似这种的

我们需求也是这样的,没有合适的组件满足

这种我今天自己写了一个,明天发一个在插件市场,之前还写过类似京东的多级联动插件,和这个有点区别

写了吗

回复 1***@qq.com: 发在插件市场

回复 kim猴: 大神,发布的名字叫什么?

在uni-app中,虽然没有官方的城市多级联动组件,但你可以通过自定义组件和API调用实现这一功能。以下是一个简单的示例,展示了如何实现省、市、区/县三级联动。

首先,你需要一个包含所有城市数据的JSON文件(这里假设为cityData.json),其结构大致如下:

[
    {
        "name": "北京市",
        "children": [
            {
                "name": "北京市",
                "children": [
                    {"name": "东城区"},
                    {"name": "西城区"},
                    // 更多区县
                ]
            }
        ]
    },
    {
        "name": "上海市",
        "children": [
            {
                "name": "上海市",
                "children": [
                    {"name": "黄浦区"},
                    {"name": "徐汇区"},
                    // 更多区县
                ]
            }
        ]
    },
    // 更多省份
]

接下来,创建一个自定义组件CityPicker.vue,用于实现城市多级联动:

<template>
  <view>
    <picker mode="selector" :range="provinceNames" @change="onProvinceChange">
      <view class="picker">{{ selectedProvince }}</view>
    </picker>
    <picker mode="selector" :range="cityNames" @change="onCityChange" v-if="cities.length">
      <view class="picker">{{ selectedCity }}</view>
    </picker>
    <picker mode="selector" :range="countyNames" @change="onCountyChange" v-if="counties.length">
      <view class="picker">{{ selectedCounty }}</view>
    </picker>
  </view>
</template>

<script>
import cityData from '@/assets/cityData.json';

export default {
  data() {
    return {
      cityData,
      selectedProvince: '',
      selectedCity: '',
      selectedCounty: '',
      provinceNames: [],
      cities: [],
      cityNames: [],
      counties: [],
      countyNames: []
    };
  },
  methods: {
    // 初始化省份列表
    initProvinces() {
      this.provinceNames = this.cityData.map(province => province.name);
      this.onProvinceChange(0);
    },
    // 省份变化时更新城市和区县
    onProvinceChange(e) {
      const province = this.cityData[e];
      this.cities = province.children;
      this.cityNames = this.cities.length ? this.cities[0].children.map(city => city.name) : [];
      this.onCityChange(0);
    },
    // 城市变化时更新区县
    onCityChange(e) {
      const city = this.cities[0].children[e];
      this.counties = city.children;
      this.countyNames = this.counties.map(county => county.name);
      this.onCountyChange(0);
    },
    // 区县变化处理
    onCountyChange(e) {
      this.selectedCounty = this.countyNames[e];
    }
  },
  mounted() {
    this.initProvinces();
  }
};
</script>

在这个示例中,我们使用了uni-app的picker组件来展示选择框,并通过监听change事件来实现联动效果。你需要根据实际情况调整cityData.json的数据结构,并在组件中做相应的处理。这个示例只是一个基本的实现,你可以根据需求进行扩展和优化。

回到顶部