微信小程序——自定义键盘:自定义组件和父组件通过事件进行属性同步

微信小程序——自定义键盘:自定义组件和父组件通过事件进行属性同步

  1. 自定义组件触发事件时,需要在自定义组件中使用 triggerEvent 方法,指定事件名、detail对象和事件选项:
  2. 在对组件进行封装时 在当前页面想要获取组件中的某一状态,需要使用到this.triggerEvent(’ ',{},{}),第一个参数是自定义事件名称,这个名称是在页面调用组件时bind的名称,第二个对象就可以将想要的属性拿到,第三个参数文档中有介绍。

3.组件中的方法要在调用组件的wxml中全部声明,否则不起作用
4.亮点:

  • 键盘样式人性化
  • 可跳转键盘
  • 对车牌号长度有校验
  • 对车牌号有正则校验

1. 页面样式

微信小程序——自定义键盘:自定义组件和父组件通过事件进行属性同步_第1张图片
微信小程序——自定义键盘:自定义组件和父组件通过事件进行属性同步_第2张图片

2.业务需求

自定义键盘,先触发地域键盘,再触发数字字母键盘,字母键盘可以返回到地域键盘。

3.项目结构

addcar中调用组建panel的方法
微信小程序——自定义键盘:自定义组件和父组件通过事件进行属性同步_第3张图片

3.代码

一、组件的内容
panel.js


Component({

  externalClasses: ['v-panel'],

  properties: {
    isShow: {
      type: Boolean,
      value: false,
    },
    buttonBorder: {
      type: String,
      value: "1px solid #ccc"
    },
    backgroundColor: {
      type: String,
      value: "#fff"
    },
    //1为省份键盘,其它为英文键盘
    keyBoardType: {
      type: Number,
      value: 1,
    }
  },
  data: {
    keyVehicle1: '京沪粤津冀豫云辽黑湘',
    keyVehicle2: '皖鲁新苏浙赣鄂桂甘',
    keyVehicle3: '晋蒙陕吉闽贵渝川',
    keyVehicle4: '青藏琼宁使领',
    keyNumber: '1234567890挂',
    keyEnInput1: 'QWERTYUIOP学',
    keyEnInput2: 'ASDFGHJKL警',
    keyEnInput3: 'ZXCVBNM港澳',
  },
  methods: {
    vehicleTap: function (event) {
      console.log("panel")
      let val = event.target.dataset.value;
      console.log("panel:"+val)
      switch (val) {
        case 'delete':
          this.triggerEvent('delete');
          this.triggerEvent('inputchange');
          break;
        case 'ok':
          this.triggerEvent('ok');
          break;
        case 'back':
          this.triggerEvent('back');
          console.log("返回")
          break;
        default:
          this.triggerEvent('inputchange', val);
      }
    },
  }
});

panel.json

{
  "component":true
}

panel.wxml


  
  
    
      {{item}}
    
    
      {{item}}
    
    
      {{item}}
    
    
      {{item}}
       
        删除
      
    
  
  
  
    
      {{item}}
    
    
      {{item}}
    
    
      {{item}}
      
        删除
      
    
    
    返回
      {{item}}
      确定
    
  











panel.wxss

:host {
  width: 100%;
}
.vehicle-panel {
  width: 100%;
  position: fixed;
  bottom: 0;
  display:flex;
  flex-direction:column;
  justify-content:center;
  z-index: 1000;
}
.vehicle-panel-row {
  text-align: center;
  font-size: 0;
  margin: 5rpx 0;
}
.row{
  display: flex; 
  justify-content: space-between; 
  align-items: center;
}
.vehicle-panel-row-last{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.vehicle-panel-row-button {
  display: inline-block;
  vertical-align: middle;
  background-color: #fff;
  margin: 2.5rpx;
  padding: 5rpx;
  width: 70rpx;
  height: 90rpx;
  text-align: center;
  line-height: 80rpx;
  border-radius: 10rpx;
  box-sizing: border-box;
  font-size: 40rpx;
}
.button{
  background-color: #fff;
  margin: 5rpx;
  padding: 5rpx;
  width: 80rpx;
  height: 80rpx;
  text-align: center;
  line-height: 80rpx;
  border-radius: 10rpx;
  
}
.vehicle-panel-row-button-number {
  background-color: #eee;
}
.vehicle-panel-row-button-last {
  width: 90rpx;
  height: 90rpx;
  line-height: 80rpx;
}
.vehicle-hover {
  background-color: #ccc;
}
.vehicle-panel-row-button-img {
  /* display: flex; */
  /* justify-content: center; */
  /* align-items: center; */
  display: inline-block;
  vertical-align: middle;
  width: 100rpx;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
}
.vehicle-panel-row-button-img1 {
  /* display: flex; */
  /* justify-content: center; */
  /* align-items: center; */
  display: inline-block;
  vertical-align: middle;
  width: 70rpx;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
}
.vehicle-panel-img-hover{
  background-color:white;
}
.vehicle-en-button-delete {
  width:100%;
  height:100%;
}
.vehicle-panel-ok {
  background-color: #2F6BB4;
  color: #fff;
  width: 150rpx;
  height: 80rpx;
  font-size: 15px;
}

二、页面调用组件
1.addcar.js

require("../../utils/trade.js");

var e = require("../../utils/request.js"), token = require("../../utils/token.js"), t = require("../../utils/util.js").today, a = getApp();

Page({
  data: {
    show:false,//车辆>0,为true;<0,为false
    modal:false,//弹窗,默认false
    cars: [],
    territory: "",
    plateNo: "",
    isShow:false,
    keyBoardType:1,
  },
  onLoad: function (options) {
    let ts = this;
    ts.selectCar()
  },
  selectCar:function(){
    var ts = this
    e.request('/v1/associators?Corporation=park&openid=' + wx.getStorageSync('openid'),
      {}, 'GET').then((res) => {
        console.log('查询')
        console.log(res)
        if (res.statusCode == '200' && res.data.list[0].car_parks) {
          console.log(res.data.list[0].car_parks)
          ts.setData({cars:res.data.list[0].car_parks,show:true})
        }else{
          ts.setData({show: false})
        }
      })
  },
  deleteCar:function(deleteRes){
    let ts = this;
    wx.showModal({
      title: '提示',
      content: '您确认解绑该辆车吗?',
      success:function(res){
        if(res.confirm){
          //调用后台接口——解绑——>成功后提示解绑成功,刷新页面
          // console.log('删除')
          // console.log(deleteRes)
          // console.log((deleteRes._relatedInfo.anchorRelatedText + '').slice('5','-1'))
          e.request('/managementchanel/DeleteCarbind?parkid=' + a.globalData.parkid,
            {
              usr_num: deleteRes.currentTarget.dataset.id,
              openid:wx.getStorageSync('openid')
            }, 'POST').then((res) => {
              console.log('delete:')
              console.log(res)
              if (res.statusCode == '200' && res.data.return_code==='00') {
                wx.showToast({
                  title: '解绑成功',
                  duration:2000,
                  success: function () {
                    // ts.onLoad()
                    setTimeout(function () {
                      ts.selectCar()
                    },2000);
                  }
                });         
              }else{
                wx.showToast({
                  title: '解绑失败,请重试',
                  icon:'none'
                })
              }
            })
        }
      }
    })
  },
  addCarBtn:function(){
    let ts = this;
    ts.setData({
      modal:true,
      plateNo:'',
      isShow:true,
      keyBoardType:1,
    })
     
    console.log('modal:'+ts.data.modal)
  },
  closeModal:function(){
    this.setData({
      modal:false,
      plateNo:'',
      isShow:false,
    })
  },
  carNum:function(e){
    console.log(e.detail.value)
    this.setData({
      input: e.detail.value
    })
  },
  saveBtn:function(){
    //校验车牌号是否规范
    // console.log(this.data.input)
    let ts = this
    let carNum = ts.data.plateNo
    let reg =/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z][A-Z][A-Z0-9]{4}[A-Z0-9挂学警港澳]$/
   
    if (carNum == ''||carNum === undefined){
      wx.showToast({
        title: '请输入车牌号',
        icon:'none'
      })
    } else if (carNum.match(reg)){
        //调用后台绑定车辆接口
        //绑定成功或重复或失败,要刷新页面
      console.log('parkid')
      console.log(a.globalData.parkid)
      //增改车辆pk201901181214000001
      e.request('/managementchanel/woaBind?parkid=' + a.globalData.parkid,
        {
          usr_num: carNum,
          openid:wx.getStorageSync('openid')
        }, 'POST').then((res) => {
          console.log(res)
          if (res.statusCode == '200' && res.data.return_code === '00' && res.data.resp_msg==='绑定成功'){
            wx.showToast({title: '绑定成功',duration:1000, })
            ts.setData({modal: false,isShow:false, keyBoardType: 1 })
            setTimeout(function () {ts.selectCar()}, 1000);
          } else if (res.data.resp_msg === "此车牌号已绑定"){
            wx.showToast({title: '此车牌号已绑定',icon:'none',complete:function(){ ts.setData({ keyBoardType: 1 })}})
          }else{
            wx.showToast({title: '绑定失败',icon:'none',complete:function(){ ts.setData({ keyBoardType: 1 })}})           
          }
        })
    }else{
      wx.showToast({title: '请核对车牌号',icon:'none', complete:function(){ts.setData({ keyBoardType: 1 }) } })
   }
  },

  //开启 地域选择键盘+车牌选择键盘
  openInput: function () { this.setData({ isShow: true, keyBoardType: 1 });
    if(this.data.plateNo==7)return
   },

  //关闭键盘
  close: function () { this.setData({ isShow: false }); },

  //点击了删除
  delete: function (e) {
    this.setData({ plateNo: this.data.plateNo.substring(0, this.data.plateNo.length - 1) });
    if(this.data.plateNo.length==0) this.setData({keyBoardType:1})
  },

  //点击键盘
  click: function (e) {
    var val = e.detail;
    if (!val) return;

    //汉字 正则表达式
    var reg = new RegExp('[u4E00-u9FFF]+', 'g');//一个或多个汉字,
    if (!reg.test(val)) {
      if (this.data.plateNo.length < 7) { var ts = this; ts.setData({ territory: val, keyBoardType: 2, plateNo: this.data.plateNo + val });}
    }else {
      if (this.data.plateNo.length  >= 7) return;
      this.setData({ plateNo: this.data.plateNo + val });
    }
 },
//点击了 小键盘确认
  ok: function (e) {this.setData({ isShow: false }); },
//点击返回到地域键盘
  back: function (e) {this.setData({ keyBoardType:1});},

  onShow: function () { },
  onShareAppMessage: function (e) { },
  onReachBottom: function () {},
});

2.addcar.json

{
  "navigationBarTitleText": "绑定车辆",
  "navigationBarBackgroundColor": "#2F6BB4",
  "component": true,
  "usingComponents": {"v-panel": "../panel/panel"}
}

3.addcar.wxml


    
        
            
                
                    已绑车辆
                    {{car.platecard}}
                    
                
            
            
                添加 
                添加车辆
            
        
    
    
    
        
        
            
                添加车辆
                 
            
            
                
                
            
            
                
            
        
    


//调用组件:声明组件里的方法 ——>在addcar.js中找到相应的方法设置属性

4.addcar.wxss

.modal{
    /* display: none; */
    position: fixed;
    top: 0;
    left: 0;
    z-index: 100;
    width:100vw;
    height: 100vh;
}
    .mask{
        position: absolute;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        background: rgba(0,0,0,.5);
        z-index: -1;
    }
    .modal-content{
      width:550rpx;
      height:280rpx;
      margin:400rpx 100rpx;
      border-radius:5px;
      background:#FFFFFF;
      position:relative;

    }
    .modal-header{
        padding: 20rpx;
        border-bottom: 2px solid #CCCCCC;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .modal-title{
        font-weight: bold;
        font-size: 15px;
        max-width: 90%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .modal-body{

    }
    .modal-footer{}
  

.icon{
  width:40rpx;
  height:40rpx;
  display:inline-block;
  vertical-align:middle;
  margin:0 20rpx;
}
    .full-container{
        display: inline-block;
        min-height: 100vh;
        width: 100%;
        background:  #F2F2F2;
    }
    .cell{
        height: 0.58rpx;
        padding: 0 0.2rpx;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-bottom: 0.1rpx;
        background: #FFFFFF;
    }
    .cell-name{
        color: #8A8A8A;
    }
    .cell-value{}
    .cars{
      background:#FFFFFF;
      padding:20rpx 20rpx 0;
      line-height:30rpx;

    }
    .car-list{
        border-bottom: 1px solid #CCCCCC;
        padding-bottom: 0.1rpx;
    }
    .tip-text{
        width: 2.6rpx;
        color: #666;
        line-height: 0.24rpx;
        margin: 0.3rpx auto;
    }
    .add-btn{
      color:#63C1ED;
      padding:30rpx 0;
      font-size:15px;
      display:flex;
      align-items:center;
      cursor:pointer;

    }
.btn{
  display:flex;
  justify-content:center;
  align-content:center;
  align-items:center;
  background:#2F6BB4;
  border-color:#2F6BB4;
  color:#FFFFFF;
  height:60rpx;
  width:250rpx;
  font-size:15px;
  vertical-align:middle;
  text-align:center;
  text-decoration:none;
  cursor:pointer;
  margin-top:15rpx;
  border-radius:30px;
}
.input{
  border-bottom:1px solid #E5E5E5;
  min-width:518rpx;
  padding:16rpx;
  margin-bottom:20rpx;
  font-size:15px;
  display: inline-block;
}
.field{
    display: flex;
    justify-content: flex-start;
    padding: 30rpx 10rpx;
    font-size: 15px;
}
.label{
    width:200rpx;
    margin-right:10rpx;
    color: #888888;
}
.value{
    flex-grow: 1;
}
.loading{
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 110;
    width: 100vw;
    height: 100vh;
    background: rgba(0,0,0,.1);
}
    .loading-box{
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        width: 120px;
        height: 120px;
        border-radius: 4px;
        background: rgba(0,0,0,.7);
        display: flex;
        justify-content: center;
        align-items: center;
        margin: auto;
    }
    .loading-img{
        width: 50px;
        height: 50px;
        animation: circle 2s linear infinite;
    }

你可能感兴趣的:(微信小程序,停车场项目)