微信小程序-点击事件、跳转、双向绑定

1,671 阅读3分钟

原生小程序

一、点击事件-原生小程序

事件 - 微信官方文档 · 小程序

1.1、按钮点击事件

<!-- 绑定了一个change事件,并传递type属性值为0 -->
<button data-type="0" bindtap="change">点我改变</button>

// change事件
change(event: any) {
    // 获取按钮参数
    let type = event.currentTarget.dataset.type;
    console.log("type==>>", type)
}

1.2、view标签点击事件

<!-- 绑定了一个toDetail事件,并传递id属性,值动态获取 -->
<!-- hover-class 添加点击效果 -->
<view data-id="{{weight.id}}" bindtap="toDetail" hover-class="highSelectColor">
</view>

.highSelectColor{
    // 添加点击效果
    background-color: yellow;
}

onShow() {
    // 设置参数
    this.setData({
        identifier: wx.getStorageSync("currentUser")
    })
    console.log("onShow==>>", this.data.lidentifier)
},

// toDetail事件
toDetail(event: any) {
    console.log("id==>>", event.currentTarget.dataset.id)
    // 页面跳转
    wx.navigateTo({
        "url": "../../../pages/task/task_detail/index?id=" + e.currentTarget.dataset.id
    })
}

二、跳转-原生小程序

2.1、标签跳转

navigator - 微信官方文档 · 小程序

<!-- hover-class="none"时,没有点击态效果 -->
<navigator url="../signIn/signIn" hover-class="none">
    <u-icon class="item-icon" name="/static/icon/sign-in.png" size="32"></u-icon>
    <view class="item-text">每日签到</view>
</navigator>

2.2、事件跳转

wx.navigateTo - 微信官方文档 · 小程序

toWeightDetail(e: any) {
    console.log("点击过衡任务卡片", e.currentTarget.dataset.id)
    wx.navigateTo({
        "url""../../../pages/task/task_detail/index?id=" + e.currentTarget.dataset.id
    })
},

2.3、返回前两个页面

navigateBack - 微信官方文档 · 小程序

toAddAddress() {
    app.request.addressBookSave(this.data.params).then(res => {
      if (res.code != 0) {
        app.util.showModal(res.msg);
        return
      }
      let pages = getCurrentPages()
      if (pages.length > 1) {
        // 调用前两个页面的selectContact方法
        pages[pages.length - 3].selectContact(this.data.type, res.data)
        wx.navigateBack({
          delta2
        })
      }
      app.util.showToast()
    })
  },

2.4、返回上一个页面 并调用指定方法传参(有效)

radioChange(e: any) {
    let data = this.data.addressBookList.find(item => {
      return item.id === Number(e.detail.value)
    })
    console.log("【客户列表data】data==>>", data)
    let pages = getCurrentPages()
    if (pages.length > 1) {
      // 获取页面栈 并调用上一个页面的selectContact方法
      pages[pages.length - 2].selectContact(this.data.type, data)
      wx.navigateBack()
    }
  },

三、表单双向绑定、图片上传-原生小程序

<view class="header">
  <view class="content">
    <view class="font-info-title">司机信息</view>
    <van-cell-group>
      <van-field label-class="cover"
        value="{{params.driverName}}"
        data-key="driverName"
        bindinput="inputChange"
        label="姓名"
        placeholder="请输入姓名"
        clearable
        required
        border="{{ false }}" />
      <van-field label-class="cover"
        value="{{params.driverPhone}}"
        data-key="driverPhone"
        bindinput="inputChange"
        type="number"
        maxlength="11"
        label="手机"
        placeholder="请输入手机"
        clearable
        required
        border="{{ false }}" />
      <van-field label-class="cover"
        value="{{params.idCard}}"
        data-key="idCard"
        bindinput="inputChange"
        type="idcard"
        maxlength="18"
        label="身份证号"
        placeholder="请输入身份证号"
        clearable
        required
        border="{{ false }}" />
      
      <!-- =====>>下拉选<<===== -->
      <view class="section">
        <picker mode="selector"
          value="{{date}}"
          range="{{companyOptions}}"
          <!-- =====>>渲染companyOptions对象中的label属性的值,注意要加引号<<===== -->
          range-key="{{'label'}}"
          bindchange="bindCompanyChange">
          <van-field label-class="cover"
            value="{{params.contactCompany}}"
            bindinput="inputChange"
            label="收货单位"
            placeholder="请选择收货单位"
            clearable
            readonly
            required
            border="{{ false }}" />
        </picker>
      </view>
      
      <!-- =====>>时间选择器<<===== -->
      <view class="section">
        <picker mode="date" data-key="foundAtVo" bindchange="bindDateChange">
          <van-field label-class=""
            value="{{params.foundAtVo}}"
            label="成立日期"
            placeholder="请选择成立日期"
            clearable
            required
            readonly
            border="{{ false }}" />
        </picker>
      </view>
      <view class="section">
        <picker mode="date" data-key="deadlineVo" bindchange="bindDateChange">
          <van-field label-class=""
            value="{{params.deadlineVo}}"
            label="营业期限"
            placeholder="请输入营业期限"
            clearable
            required
            readonly
            border="{{ false }}" />
        </picker>
      </view>
    </van-cell-group>
  </view>
  <view class="module-employment">
    <van-uploader class="uploader"
      accept="image"
      capture="camera"
      file-list="{{drivingHomepageArr}}"
      max-count="1"
      data-index="{{0}}"
      bind:after-read="afterRead"
      bind:delete="deleteImage"
      upload-text="驾驶证主页" />
    <van-uploader class="uploader"
      accept="image"
      capture="camera"
      file-list="{{drivingAvocationArr}}"
      max-count="1"
      data-index="{{1}}"
      bind:after-read="afterRead"
      bind:delete="deleteImage"
      upload-text="驾驶证副页" />
    <van-uploader class="uploader"
      accept="image"
      capture="camera"
      file-list="{{careerImageArr}}"
      max-count="1"
      data-index="{{2}}"
      bind:after-read="afterRead"
      bind:delete="deleteImage"
      upload-text="从业资格证" />
  </view>
</view>
<view class="footer">
  <van-button custom-class="custome-but" data-status="{{true}}" bind:click="onClickAdd" type="info">我自己有车</van-button>
  <van-button custom-class="custome-but" data-status="{{false}}" bind:click="onClickAdd" type="info">我自己没车</van-button>
</view>
  
  
  --------js部分-------
  
let app = getApp<IAppOption>()
// pages/my/tran_company/index.ts
Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentDate: app.util.formatTimeTwo(new Date().getTime(), 'Y-M-D'),
    params: {
      "id": null,
      "driverName": "",
      "driverPhone": "",
      "idCard": "",
      "drivingHomepage": "",
      "drivingAvocation": "",
      "careerImage": "",
      "foundAtVo": '',
      "deadlineVo": ''
    },
    companyOptions: [],
    drivingHomepageArr: [],
    drivingAvocationArr: [],
    careerImageArr: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    wx.setNavigationBarTitle({ title: "司机注册" })
  },
  
  // 时间选择器改变监听
  bindDateChange(e: any) {
    this.setData({
      [`params.${e.currentTarget.dataset.key}`]: e.detail.value
    })
  },
  // 输入框输入事件
  inputChange(e: any) {
    this.setData({
      [`params.${e.currentTarget.dataset.key}`]: e.detail
    })
  },
  onClickAdd(e: any) {
    let status = e.currentTarget.dataset.status

    if(!this.checkParams()) return

    this.setData({
      'params.foundAt': new Date(this.data.params.foundAtVo).getTime()/1000,
      'params.deadline': new Date(this.data.params.deadlineVo).getTime()/1000,
    })

    app.request.driverRegister(this.data.params).then(res => {
      if (res.code != 0) {
        app.util.showModal(res.msg);
        return
      }
      if (status) {
        wx.navigateTo({url: "../driving_licence/index"})
      } else {
        wx.switchTab({
          url: '/pages/index/index'
        })
        app.util.showToast('注册成功');
      }
    })
  },

  checkParams() {
    if(!this.data.params.driverName) {
      app.util.showToast("请输入司机姓名", 'none')
      return false
    }
    if(!this.data.params.driverPhone) {
      app.util.showToast("请输入司机手机号", 'none')
      return false
    }
    if(!this.data.params.idCard) {
      app.util.showToast("请输入身份证号", 'none')
      return false
    }
    if(!this.data.params.drivingHomepage) {
      app.util.showToast("请上传驾驶证主页", 'none')
      return false
    }
    if(!this.data.params.drivingAvocation) {
      app.util.showToast("请上传驾驶证副页", 'none')
      return false
    }
    if(!this.data.params.careerImage) {
      app.util.showToast("请上传从业资格证", 'none')
      return false
    }
    return true
  },

  // ------------图片上传 start------------
  afterRead(e: any) {
    let index = e.currentTarget.dataset.index;
    let name = '驾照证主页'
    if (index === 1) name = '驾驶证副页'
    if (index === 2) name = '从业资格证'
    app.request.imageUpload(e.detail.file.url, { file: e.detail.file }).then(res => {
      if (res.code != 0) {
        app.util.showToast('上传失败', 'error')
        return
      }
      this.buildImageArr(res.data, name, index)
    })
  },
  deleteImage(e: any) {
    let index = e.currentTarget.dataset.index;
    if (index === 0) {
      this.setData({
        drivingHomepageArr: [],
        'params.drivingHomepage': ''
      })
    } else if (index === 1) {
      this.setData({
        drivingAvocationArr: [],
        'params.drivingAvocation': ''
      })
    } else {
      this.setData({
        careerImageArr: [],
        'params.careerImage': ''
      })
    }
  },
  buildImageArr(url: string, name: string, index: number) {
    if (index === 0) {
      this.setData({
        drivingHomepageArr: [{
          url: app.globalData.resourcePath + url,
          name: name,
        }],
        'params.drivingHomepage': url
      })
    } else if (index === 1) {
      this.setData({
        drivingAvocationArr: [{
          url: app.globalData.resourcePath + url,
          name: name,
        }],
        'params.drivingAvocation': url
      })
    } else {
      this.setData({
        careerImageArr: [{
          url: app.globalData.resourcePath + url,
          name: name,
        }],
        'params.careerImage': url
      })
    }
  },
  // ------------图片上传 end------------
})

四、单选列表、下拉刷新、数据分页

---------json页面配置部分---------
{
  "usingComponents": {
    "van-divider": "@vant/weapp/divider/index",
    "van-progress": "@vant/weapp/progress/index",
    "van-dropdown-menu": "@vant/weapp/dropdown-menu/index",
    "van-dropdown-item": "@vant/weapp/dropdown-item/index",
    "van-radio": "@vant/weapp/radio/index",
    "van-radio-group": "@vant/weapp/radio-group/index"
  },
  // 开启页面下拉刷新
  "enablePullDownRefresh": true
}

---------页面部分---------
<view style="height: 100vh; display: flex; flex-direction: column;justify-content: space-between;">
  <view class="scroll-content">
    <radio-group bindchange="radioChange">
      <label class="scroll-content-item" wx:for="{{addressBookList}}" wx:key="index">
        <view class="scroll-content-item-top">
          <view class="weui-cell__bd">
            <view class="optioned-company">{{item.contactCompany}}</view>
            <view class="optioned-person">
              <text>{{item.contactName}}</text>
              <text class="optioned-person-phone">{{item.contactMobile}}</text>
            </view>
            <view class="optioned-addr">{{item.address}}</view>
          </view>
          <view class="weui-cell__hd">
            <radio color="#2581E4" value="{{item.id}}" checked="{{optionId == item.id}}" />
          </view>
        </view>
        <view class="scroll-content-item-bottom">
          <!-- 防止事件冒泡,防止触发单选点击事件 -->
          <view data-id="{{item.id}}" catchtap="toEdit" style="margin-right: 20rpx;" class="font-edit">
            <van-icon name="edit" />
            编辑
          </view>
          <view data-id="{{item.id}}" catchtap="toDel" class="font-del">
            <van-icon name="delete-o" />
            删除
          </view>
        </view>
      </label>
    </radio-group>
  </view>
  <view class="footer">
    <navigator url="../add_address/index">
      <van-button class="custom-button" custom-class="custom-button" color="#2581E4" type="primary" square block>添加客户</van-button>
    </navigator>
  </view>
</view>

---------js部分---------
let app = getApp<IAppOption>()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pagin: {
      pn: 1,
      psize: 8,
      total: 0,
      pages: 0
    },
    addressBookList: [],
    param: {},
    type: '',
    optionId: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e: any) {
    this.init(e)
  },

  setNavigationBarTitle(title: any) {
    wx.setNavigationBarTitle({
      title: title
    })
  },
  radioChange(e: any) {
    let data = this.data.addressBookList.find(item => {
      return item.id === Number(e.detail.value)
    })
    console.log("【客户列表data】data==>>", data)
    let pages = getCurrentPages()
    if (pages.length > 1) {
      // 获取页面栈 并调用上个页面的selectContact方法
      pages[pages.length - 2].selectContact(this.data.type, data)
      wx.navigateBack()
    }
  },
  toEdit(e: any) {
    wx.navigateTo({
      "url": "../add_address/index?id=" + e.currentTarget.dataset.id
    })
  },
  toDel(e: any) {
    app.util.showModal("确定要删除么").then((res: any) => {
      if (res) {
        if (e.currentTarget.dataset.id === this.data.optionId) {
          app.util.showToast('不能删除已选中地址', 'none')
          return
        }
        app.request.addressBookDel({ 'id': e.currentTarget.dataset.id }).then(res => {
          if (res.code != 0) {
            app.util.showModal(res.msg);
            return
          }
          this.resetPage();
          this.getAddressBookList((addressBookList: any) => {
            this.setData({
              addressBookList: addressBookList,
            })
          });
        })
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    wx.showLoading({ title: '加载中...', })
    this.resetPage();
    this.getAddressBookList((addressBookList: any) => {
      this.setData({
        addressBookList: addressBookList
      })
      //隐藏loading 提示框
      wx.hideLoading();
      //停止下拉刷新
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.pagin.pn >= this.data.pagin.pages) {
      return;
    }
    this.setData({
      'pagin.pn': this.data.pagin.pn + 1
    })
    this.getAddressBookList((addressBookList: Array<Object>) => {
      let data: any = this.data.addressBookList;
      data.push(...addressBookList);
      this.setData({
        addressBookList: data
      })
    });
  },

  init(e: any) {
    console.log("【optionId】eeeeeee==>>", e)
    if (e) {
      this.setData({
        type: e.type,
        optionId: Number(e.id)
      })
      if (e.type === 'consigner') {
        this.setNavigationBarTitle("客户列表-发")
      } else if (e.type === 'consignee') {
        this.setNavigationBarTitle("客户列表-收")
      }
    }

    this.resetPage();
    this.getAddressBookList((addressBookList: any) => {
      console.log("【optionId】this.data.optionId==>>", this.data.optionId)
      this.setData({
        addressBookList: addressBookList
      })
    });
  },

  resetPage() {
    this.setData({
      pagin: {
        pn: 1,
        psize: 8,
        total: 0,
        pages: 0
      }
    })
  },

  /**
   * 地址簿列表
   * @param callback 
   */
  getAddressBookList(callback: any = undefined) {
    let requestData = {};
    requestData['pagin'] = this.data.pagin;
    requestData['filter'] = this.data.param;

    app.request.getAddressBookList(requestData).then(res => {
      if (res.code != 0) {
        app.util.showToast(res.msg, "error")
        return
      }
      this.setData({
        pagin: res.data.pagin
      })
      res.data.rows.forEach(e => {
        e.createAt = app.util.formatTimeTwo(e.createAt, 'Y-M-D')
      });
      callback(res.data.rows)
    })
  },
})

uni-app

一、Uni-App-点击事件

1.1、按钮方式点击

button点击 - uni-app · 小程序

<u-button shape="circle" color="#fadeb7" size="mini" text="了解一下" @click="bannerClick(2)">
</u-button>

二、Uni-App-跳转

navigator - uni-app · 小程序

<!-- hover-class="none"时,没有点击态效果 -->
<navigator url="../signIn/signIn" hover-class="none">
    <u-icon class="item-icon" name="/static/icon/sign-in.png" size="32"></u-icon>
    <view class="item-text">每日签到</view>
</navigator>