热心的web市民 2024-12-20 16:02 采纳率: 60%
浏览 69

为什么小程序使用van-cascader数据不回显呢?


<van-popup show="{{ area.show }}" round position="bottom">
  <van-cascader
    wx:if="{{ area.show }}"
    value="{{ area.cascaderValue }}"
    title="请选择户籍所在地"
    options="{{ area.options }}"
    field-names="{{ area.fieldNames }}"
    bind:close="areaClose"
    bind:change="areaChange"
    bind:finish="areaFinish"
  />
</van-popup>

area: {
      show: true,
      cascaderValue: [],
      options: [], // 初始化时只加载省份
      fieldNames: {
        text: 'name',
        value: 'id',
        children: 'children'
      },
    },
  onLoad: function (options) {
    this.loadProvinces();
  },
loadProvinces: async function () {
    const provinces = await this.getArea('province');
    this.setData({
      'area.options': provinces,
      'area.cascaderValue': [] // 重置级联选择器的值
    });
  },
  async getArea(type, parentID, cityID) {
    console.log(type);
    const res = await api.http({
      url: '/apply/getArea',
      data: {
        type: type,
        province_id: type === 'city' ? parentID : null,
        city_id: type === 'area' ? parentID : null,
        token: wx.getStorageSync('token')
      }
    });
    return res.data.map(area => ({
      ...area,
      children: [] // 初始化子项为空数组
    }));
  },
  async areaChange(e) {
    console.log(e.detail);
    const {
      value: id,
      tabIndex
    } = e.detail;
    console.log(id);
    if (tabIndex < 2) {
      const nextType = ['city', 'area'][tabIndex];
      const newArea = await this.getArea(nextType, id);
      // 获取this.data.area.options中对应的id的下标
      const selectedIndex = this.data.area.options.findIndex(option => option.id === id);
      console.log(selectedIndex);
      let that = this;
      this.setData({
        [`area.options[${selectedIndex}].children`]: newArea,
      });
    }
  },

每次获取省/市/区都需要走一下getArea函数

  • 写回答

1条回答 默认 最新

  • 道友老李 JWE233286一种基于机器视觉的水表指针读数识别及修正的方法 专利发明者 2024-12-21 04:01
    关注
    让【道友老李】来帮你解答,本回答参考通义千问大模型编写,并整理提供,如果还有疑问可以点击头像关注私信或评论。
    如果答案让您满意,请采纳、关注,非常感谢!
    ### 问题分析

    根据你提供的代码片段,getArea 函数每次获取省、市、区数据时都会触发网络请求。这不仅增加了服务器的负担,也可能导致用户体验不佳,尤其是在用户频繁切换选项时。

    为了优化这一过程,我们可以考虑以下几点: 1. 缓存机制:将已经获取过的省、市、区数据缓存起来,避免重复请求。 2. 异步加载:只在需要时加载下一级数据,而不是一次性加载所有数据。 3. 错误处理:确保在网络请求失败时有合理的处理逻辑。

    解决方案

    1. 引入缓存机制

    我们可以在 data 中添加一个 cache 对象,用于存储已经获取过的省、市、区数据。这样可以避免重复请求。

    2. 修改 getArea 函数

    getArea 函数中,首先检查缓存中是否存在所需数据,如果存在则直接返回缓存数据;如果不存在,则发起网络请求并更新缓存。

    3. 修改 areaChange 函数

    areaChange 函数中,使用缓存机制来减少不必要的网络请求。

    示例代码

    Page({
      data: {
        area: {
          show: false,
          cascaderValue: [],
          options: [], // 初始化时只加载省份
          fieldNames: {
            text: 'name',
            value: 'id',
            children: 'children'
          }
        },
        cache: {} // 添加缓存对象
      },
    
      onLoad: function (options) {
        this.loadProvinces();
      },
    
      loadProvinces: async function () {
        const provinces = await this.getArea('province');
        this.setData({
          'area.options': provinces,
          'area.cascaderValue': [] // 重置级联选择器的值
        });
      },
    
      async getArea(type, parentID) {
        console.log(type);
        
        // 检查缓存中是否存在数据
        if (this.data.cache[type] && this.data.cache[type][parentID]) {
          return this.data.cache[type][parentID];
        }
    
        const res = await api.http({
          url: '/apply/getArea',
          data: {
            type: type,
            province_id: type === 'city' ? parentID : null,
            city_id: type === 'area' ? parentID : null,
            token: wx.getStorageSync('token')
          }
        });
    
        const data = res.data.map(area => ({
          ...area,
          children: []
        }));
    
        // 更新缓存
        if (!this.data.cache[type]) {
          this.data.cache[type] = {};
        }
        this.data.cache[type][parentID] = data;
    
        return data;
      },
    
      async areaChange(e) {
        console.log(e.detail);
        const { value: id, tabIndex } = e.detail;
        console.log(id);
    
        if (tabIndex < 2) {
          const nextType = ['city', 'area'][tabIndex];
          const newArea = await this.getArea(nextType, id);
    
          // 获取 this.data.area.options 中对应的 id 的下标
          const selectedIndex = this.data.area.options.findIndex(option => option.id === id);
          console.log(selectedIndex);
    
          this.setData({
            [`area.options[${selectedIndex}].children`]: newArea
          });
        }
      },
    
      areaClose() {
        this.setData({
          'area.show': false
        });
      },
    
      areaFinish(e) {
        console.log('finish:', e.detail);
        // 处理完成后的逻辑
      }
    });
    

    关键点说明

    1. 缓存机制:通过 this.data.cache 存储已经获取过的省、市、区数据,避免重复请求。
    2. 异步加载:只在需要时加载下一级数据,提升性能和用户体验。
    3. 错误处理:虽然示例代码中没有详细展示,但在实际开发中应加入适当的错误处理逻辑,如网络请求失败时提示用户或重试机制。

    总结

    通过引入缓存机制和优化 getArea 函数,可以有效减少不必要的网络请求,提升应用的性能和用户体验。希望这个解决方案对你有所帮助!如果有任何问题或需要进一步优化,请随时告知。

    评论

报告相同问题?

问题事件

  • 创建了问题 12月20日