La selección en cascada de Vant Cascader utiliza el subprograma wx

El proceso principal de usar la selección en cascada de Vant es usarlo de acuerdo con el valor de las opciones. Si necesita personalizar, puede procesar la información obtenida de la API en el estilo de las opciones a través de un algoritmo y luego usarla.

En primer lugar, usaremos los componentes vant en el subprograma WeChat. Aquí citaremos directamente sin demasiada introducción.

<!-- 提示:vant组件给的样式,可以根据需求更改 -->
<view style="height:30rpx;"></view>
<view>
  <van-field value="{
    
    { fieldValue }}" is-link readonly label="选择门锁" placeholder="请选择楼宇-房间号" bind:tap="onClick1" style="font-weight: 700;" />
  <van-popup show="{
    
    { show }}" round position="bottom">
    <van-cascader wx:if="{
    
    { show }}" value="{
    
    { cascaderValue }}" title="请选择所在地区" options="{
    
    { options }}" active-color="#d7000f" bind:close="onClose1" bind:change="onChangeFiled" bind:finish="onFinish1" />
  </van-popup>
</view>

Luego observamos que este componente está implementado por vant-field y vant-cascader. Determine si mostrar el componente cascader de acuerdo con el parámetro show:true/false. El cascaderValue es el resultado obtenido al final y se puede usar de acuerdo con sus propias necesidades. Las opciones de parámetros son la información más importante aquí, que es mostrar el contenido en el cuadro de enlaces múltiples. El estilo fijo de las opciones proporcionadas por vant, el formato de los parámetros no debe modificarse, pero vant dio oficialmente la modificación, y los campos internos pueden modificarse.

options = [
  {
    text: '浙江省',
    value: '330000',
    children: [{ text: '杭州市', value: '330100' }],
  },
  {
    text: '江苏省',
    value: '320000',
    children: [{ text: '南京市', value: '320100' }],
  },
];

La siguiente es una pequeña demostración de la demostración del subprograma WeChat.

//微信小程序data中定义的数据
data:{
    value: '',
    show: false,
    //options 中给的null字段是为了防止我们请求时没有数据造成的,组件原始数据展示出来的bug
    options: [{
          text: 'null',
          value: '',
          children: [],
        }],
    cascaderValue: "",
    myRoomid:'',
    myRoominfo:''
}

// 复联框
  onClick1() {
    this.setData({
      show: true,
    });
  },

  onClose1() {
    this.setData({
      show: false,
    });
  },
// vant 给出的函数用于,监听复联框组件结束的事件
 onFinish1(e) {
    const { selectedOptions, value } = e.detail;
    const fieldValue = selectedOptions
        .map((option) => option.text || option.name)
        .join('-');
    const myPlace = selectedOptions.map((option) => option.text)
    // 我现在需要匹配一下id
    //查找对应的函数
    this.setData({
      myPlace,
      fieldValue,
      cascaderValue: value,
    })
    console.log("我的楼宇",this.data.myPlace);
    console.log("我的房间信息",this.data.myRoominfo);
    let array = this.data.myRoominfo
    //查找对应的函数
    const myList = array.find(function(array,index,arrs){
      return array.building == myPlace[0] && array.name == myPlace[1]
    })
    console.log("过滤",myList);
    this.setData({
      roomId:myList.id,
      checked1: myList.lock1Status == 1 ? false:true,
      checked:myList.lock1Status == 1 ? false:true
    })
    console.log("roomid",this.data.roomId);
    this.setData({
      show:false
    })
  },

//在微信小程序加载的时候通过 api获得数据,并且为了迎合vant组件的样式写的笨拙的算法,求大佬修改一下!
onLoad(options) {
    //wx小程序自带的请求api
    wx.request({
      url: 'http://localhost:8000/room/myRoom',
      method: 'GET',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
          //这个数据是通过用户唯一的标识符id所获取的
        "token": wx.getStorageSync('token'),
      },
      success: (res) => {
        console.log("data:", res);
        // 把我的所有房间的参数拿到
        this.setData({
          myRoominfo:res.data.data
        })
        //开始使用笨拙的算法处理vant组件所需要的options参数的样式
        let array = res.data.data 
        // 转接数组,这里定义了一个和options相似的变量 myoptions方便对options直接赋值    
        //因为wx小程序的this.setdata({})对数组对象的单独赋值有些困难
        var myOptions = [{
          text: '浙江省',
          value: '330000',
          children: [],
        }]
/*
api获得的数据样式:
0: {building: "信息中心", createTime: "2023-02-27 15:51:52", deviceName: "Room204", deviceType: "有线", door1Status: "1", …}
1: {building: "信息中心", createTime: "2023-02-28 21:01:46", deviceName: "Room208", deviceType: "4G", door1Status: "1", …}
2: {building: "科技大楼", createTime: "2023-02-28 22:38:56", deviceName: "Building413", deviceType: "4G", door1Status: "1", …}


*/
        for (var i = 0; i < array.length; i++) {
          var unique = true;
          if (i == 0) {
            myOptions[i].text = array[i].building
            myOptions[i].value = i
            myOptions[i].children.push({ text: `${array[i].name}`, value: i })
            continue;
          }
          for (var idx = 0; idx < myOptions.length; idx++) {
            if (myOptions[idx].text == array[i].building) {
              myOptions[idx].children.push({ text: `${array[i].name}`, value: i })
              unique = false;
              continue;
            }
          }
          if (unique) {
            myOptions.push({
              text: `${array[i].building}`,
              value: i,
              children: [{ text: `${array[i].name}`, value: i }],
            })
          }
        }
        this.setData({
          options:myOptions
        })
        console.log("options",myOptions);
      }
    })
  },

//数据处理后的样式 最后只要把这个值传给options就可以了 复联框就可以正常使用
/*0:
children: Array(2)
0: {text: "204", value: 0}
1: {text: "208", value: 1}
length: 2
nv_length: (...)
__proto__: Array(0)
text: "信息中心"
value: 0
__proto__: Object
1:
children: Array(1)
0: {text: "413", value: 2}
length: 1
nv_length: (...)
__proto__: Array(0)
text: "科技大楼"
value: 2*/

Supongo que te gusta

Origin blog.csdn.net/LKX_S/article/details/129410595
Recomendado
Clasificación