微信小程序封装组件 点击按钮改变样式 ,实现搜索

<!--btn选择 -->
<view class="name_btns ">
	<!-- <view> </view> -->
	<view class="cleanLevelList">
		<view wx:for="{{propBtns}}" wx:key="index"
        class="workerTypeBtn" >
			<button size="mini" bindtap="ChangeBtn" data-id="{{item.id}}"
   class=
"{{item.isBlue?'isBlue changeBtn mybtn-class':'changeBtn mybtn-class'}}">
{{item.name}}</button>
		</view>
	</view>
</view>
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    propBtns: {
      type: Array,
    },
  },
  externalClasses: ["mybtn-class"], //在这里定义接收父组件传递的class名 可以是多个class名
  /**
   * 组件的初始数据
   */
  data: {},
  created() {},
  attached() {
    // console.log(this.properties.propBtns);
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 获取点击的值
    ChangeBtn(e) {
     //这里的id其实相当于index来用的
      let id = e.target.dataset.id;
      let value = this.properties.propBtns[id];
    
      let list = this.properties.propBtns;
      list.forEach((el, index) => {
        var name = "isNoBlue" + index;
        name = `propBtns[${index}].isBlue`;
        this.setData({
          [name]: false,
        });
      });

      let isBlue = `propBtns[${e.currentTarget.dataset.id}].isBlue`;

      this.setData({
        [isBlue]: true,
      });
      this.triggerEvent("ChangeBtn", value);
    },
    
  },
});

.name_btns {
	display: flex;
	/* justify-content: space-between; */
	align-items: center;
	font-size: 10px;
}

.cleanLevelList {
	display: flex;
	justify-content: left;
	flex-wrap: wrap;
	padding-top: 10px;
}

.isBlue {
	background-color: #1486E6;
	color: white;

}

.changeBtn {
	padding-top: 0 !important;
	padding-bottom: 0 !important;
	margin: 0 5px !important;
	font-size: 12px !important;

}

引用方式:在需要引用的页面json文件里引入 "SearchBtn": "/Component/SearchBtn/SearchBtn"

 "组件命名": "你的组件位置"

例如:

	"usingComponents": {
		"SearchBtn": "/Component/SearchBtn/SearchBtn"
	},

在wxml里引入,我命名的是SearchBtn

<SearchBtn prop-btns="{{deviceStatusList}}" 
      bindChangeBtn="deviceStatusClick" 
      mybtn-class="mybtnClass">
</SearchBtn>
<!-- prop-btns 是定义在组件里接收父组件传递的值的名称   bind+ChangeBtn是定义在子组件里传递给父组件的点击事件-->

js里写入传入的数组格式

deviceStatusList: [
//拿id当index来用了
      {
        id: "0",
        name: "全部",
        isBlue: true,
      },
      {
        id: "1",
        name: "在线",
        isBlue: false,
      },
      {
        id: "2",
        name: "离线",
        isBlue: false,
      },
    ],

js里用点击事件获取点击的值

// 选择设备状态
  deviceStatusClick(e) {
    console.log(e.detail);
  },

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值