微信小程序 checkbox 实现双向绑定以及特殊交互处理

wxml文件代码如下:

html 复制代码
<!--页面顶部 引入wxs文件-->
<wxs module="tools" src="../../filter/tools.wxs"></wxs>
...
<checkbox-group bindchange="checkboxChange">
  <label class="weui-cell weui-check__label" wx:for="{{cancerItems}}" wx:key="value">
    <view class="weui-cell__hd">
      <checkbox value="{{item.value}}" checked="{{tools.getIncludes(checkedCancers, item.value)}}"/>
    </view>
    <view class="weui-cell__bd">{{item.name}}</view>
  </label>
</checkbox-group>

js代码如下:

javascript 复制代码
Page({
	data: {
		// 癌种
		cancerItems: [
		  {value: 'fou', name: '否'},
		  {value: 'fei', name: '肺癌'},
		  {value: 'ruxian', name: '乳腺癌'},
		  {value: 'wei', name: '胃癌'},
		  {value: 'gan', name: '肝癌'},
		  {value: 'qita', name: '其他'}
		],
		checkedCancers: [], // 选择的癌种
	},
	checkboxChange (event) {
	  console.log('event', event)
	  let checkedVal = event.detail.value
	  if (checkedVal[checkedVal.length - 1] === 'fou') { // 如果用户选择了"否",则其他癌种清空
	    checkedVal = ['fou']
	  } else { // 如果选择癌种或者"其他","否"取消选择
	    const index = checkedVal.indexOf('fou')
	    if (index > -1) {
	      checkedVal.splice(index, 1)
	    }
	    if (checkedVal.includes('fou')) { // 如果选择"其他"
	      //
	    }
	  }
	  this.setData({
	    checkedCancers: checkedVal
	  })
	}
})

所谓tool.getIncludes 方法需要 引入 tool.wxs 文件

文件代码如下:

javascript 复制代码
var tools = {
	getIncludes: function(val, target) {
	    if(!val) return
	    if(val.indexOf(target) > -1) {
	      	return true
	    } else {
	      	return false
	    }
	}
}
module.exports = {
	getIncludes: tools.getIncludes
}

注:微信小程序提到:WXS(WeiXin Script)是内联在 WXML 中的脚本段。通过 WXS 可以在模版中内联少量处理脚本,丰富模板的数据预处理能力。另外, WXS 还可以用来编写简单的 WXS 事件响应函数

相关推荐
码云之上13 小时前
小程序 iOS 多输入框焦点乱序脱坑记
ios·微信小程序·taro
Greg_Zhong2 天前
微信小程序 + 腾讯云人体分析:从 0 到 1 实现 AI 抠图打卡合照(细节待更新~)
人工智能·微信小程序·腾讯云·ai抠图-ai打卡拍照
java1234_小锋5 天前
【免费】基于Python的微信小程序网约车(打车,在线叫车,移动出行)系统(FastAPI+Vue3) 锋哥原创出品,必属精品
微信小程序·小程序·fastapi·网约车系统·在线叫车系统
拖孩6 天前
用 AI 重解千年观音灵签,做了一个微信小程序,每天摇一摇,命运给你回应
前端·后端·微信小程序
java1234_小锋6 天前
【免费】微信小程序网约车(打车,在线叫车,移动出行)系统(SpringBoot4+Vue3) 锋哥原创出品,必属精品
微信小程序·网约车·在线叫车·移动出行
AI砖家7 天前
AI编程—微信小程序开发规范
微信小程序·小程序·notepad++·ai编程
sam-zy8 天前
微信小程序+ESP8266+Arduino 开发智能插座,有本地OTA功能
微信小程序·小程序
A24207349308 天前
微信小程序开发:常用基础语法与指令详解
微信小程序·小程序·notepad++
laboratory agent开发9 天前
2026小程序系统多维度技术与落地能力深度解析
微信小程序
laboratory agent开发11 天前
多维度拆解小程序平台:数字化经营工具的理性选择指南
微信小程序