微信小程序 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 事件响应函数

相关推荐
计算机毕设指导69 小时前
基于微信小程序的校园物品租赁与二手交易系统【源码文末联系】
spring boot·mysql·微信小程序·小程序·tomcat·maven·intellij-idea
计算机毕设指导610 小时前
基于微信小程序的水上警务通系统【源码文末联系】
java·spring boot·mysql·微信小程序·小程序·tomcat·maven
李慕婉学姐14 小时前
【开题答辩过程】以《基于uni-app框架的助学管理系统的设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
微信小程序·uni-app
爱吃的强哥14 小时前
uni-app 开发微信小程序注意点
微信小程序·小程序·uni-app
计算机毕设指导61 天前
基于微信小程序的鸟博士系统【源码文末联系】
java·spring boot·mysql·微信小程序·小程序·tomcat·maven
周杰伦fans1 天前
微信小程序信息提示组件大全
微信小程序·小程序
QQ_21696290961 天前
Spring Boot大学生社团管理平台 【部署教程+可完整运行源码+数据库】
java·数据库·spring boot·微信小程序
风月歌2 天前
基于微信小程序的学习资料销售平台源代码(源码+文档+数据库)
java·数据库·mysql·微信小程序·小程序·毕业设计·源码
多仔ヾ2 天前
微信小程序开发实战之 05-微信小程序常用 API(下)
微信小程序
半兽先生2 天前
微信小程序与web-view页面双向通信
前端·微信小程序·小程序