微信小程序开发 - 动态class绑定实现多选功能

luoxuancong2025-01-15WeApp微信小程序

开发需求

TIP

最近在做一个小程序的项目时,要实现一个多选标签的功能,发现动态绑定class名称的时候发现了一些问题,将最后实现的方法记录下来。

方法一

<!-- .wxml 文件 -->
// 定义数组中是否包含某个元素的事件,记得要在顶部定义,或者引入wxs,不然不会生效
<wxs module="m1">
    var hasItem = function(list,item) {
      var boo;
      var index = list.indexOf(item)
      if (index < 0){
        boo = false;
      }else{
        boo = true;
      }          
      return boo;       
    }
    module.exports.hasItem = hasItem;
</wxs>
<view>
    <div class="tags-content">
        <div class="title">选择<span>供应</span>产品分类</div>
        <div class="content">
            <van-grid gutter="10" column-num="3">
                <block wx:for="{{list}}" wx:key="curCode">
                		<!-- 在这里动态绑定class类名 -->
                    <van-grid-item class="{{m1.hasItem(checkSupplyList,item.curCode)?'on':''}}" use-slot data-name="{{item.curName}}" data-code="{{item.curCode}}"
                        bindtap="checkSupply">
                        {{item.curName}}
                    </van-grid-item>
                </block>
            </van-grid>
        </div>
        <div class="bottom-btn">
            <button bindtap="next" type="primary">下一步</button>
        </div>
    </div>
</view>

方法二

  // hasItem.wxs 中定义
  var hasItem = function(list,item) {
    var boo;
    var index = list.indexOf(item)
    if (index < 0){
      boo = false;
    }else{
      boo = true;
    }          
    return boo;       
  }
  module.exports.hasItem = hasItem;

  <!-- wxml中引入 -->
  <wxs src="../hasItem.wxs" module="hasItem" />

记住想要在小程序wxml中使用函数,一定得定义wxs! wxs官方文档open in new window

评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.8