您的当前位置:首页正文

【愚公系列】2022年10月 微信小程序-电商项目-收货地址功能实现

2024-11-29 来源:个人技术集锦


前言

一、收货地址功能实现

// miniprogram/pages/address-list/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    radio: 0,
    selectedAddressId: 0,
    addressList: [],
    slideButtons: [{
      type: 'warn',
      text: '删除'
    }]
  },
  //选择地址
  async onSlideButtonTap(e) {
    // e.detail.index是选择按钮的序号
    let id = e.currentTarget.dataset.id 
    console.log('slide button tap', e.detail, id)

    let res = await wx.wxp.request4({
      url:`http://localhost:3000/user/my/address/${id}`,
      method:'delete'
    })
    console.log(res);
    if (res && res.data.msg == 'ok'){
      // 处理本地数据
      let addressList = this.data.addressList
      for(let j=0;j<addressList.length;j++){
        if (addressList[j].id == id){
          addressList.splice(j, 1)
          break
        }
      }
      this.setData({
        addressList
      })
    }
  },
  //获取微信收获地址
  getAddressFromWeixin(e) {
    if (wx.canIUse('chooseAddress.success.userName')) {
      wx.chooseAddress({
        success: async (res) => {
          console.log(res);
          let addressList = this.data.addressList

          let addressContained = addressList.find(item => item.telNumber == res.telNumber)
          if (addressContained) {
            this.setData({
              selectedAddressId: addressContained.id
            })
            return
          }

          let data = {
            // id: addressList.length,
            userName: res.userName,
            telNumber: res.telNumber,
            region: [res.provinceName, res.cityName, res.countyName],
            detailInfo: res.detailInfo
          }
          let res1 = await wx.wxp.request4({
            url: 'http://localhost:3000/user/my/address',
            method:'post',
            data
          })
          console.log(res1);
          if (res1.data.msg == 'ok'){
            let item = res1.data.data 
            addressList.push(item)
            this.setData({
              addressList,
              selectedAddressId:item.id
            })
          }else{
            wx.showToast({
              title: '添加不成功,是不是添加过了?',
            })
          }
        },
      })
    }
  },
  //确认收货地址返回
  confirm(e){
    let selectedAddressId = this.data.selectedAddressId
    let addressList = this.data.addressList
    let item = addressList.find(item=>item.id == selectedAddressId)
    let opener = this.getOpenerEventChannel()
    opener.emit('selectAddress', item)
    wx.navigateBack({
      delta: 1,
    })
  },
  // 编辑回来回调这个方法
  onSavedAddress(address) {
    // console.log(address);
    let addressList = this.data.addressList
    let hasExist = addressList.some((item,index)=>{
      if (item.id == address.id){
        addressList[index] = address
        return true 
      }
      return false 
    })
    if (!hasExist){
      addressList.push(address)
    }

    this.setData({
      addressList,
      selectedAddressId: address.id
    })
  },
  //跳转到新增地址界面
  navigateToNewAddressPage(e) {
    wx.navigateTo({
      url: '/pages/new-address/index',
      success:(res)=>{
        res.eventChannel.on("savedNewAddress", this.onSavedAddress)
      }
    })
  },
  /**
   * 选择收获地址
   * @param {*} e 
   */
  onChange(event) {
    this.setData({
      selectedAddressId: event.detail,
    });
  },
  /**
   * 编辑收获地址
   * @param {*} e 
   */
  edit(e){
    console.log(e.currentTarget.dataset.id);
    let id = e.currentTarget.dataset.id
    let addressList = this.data.addressList
    let address = addressList.find(item=>item.id == id)
    wx.navigateTo({
      url: '/pages/new-address/index',
      success:(res)=>{
        res.eventChannel.emit('editAddress', address)
        res.eventChannel.on('savedNewAddress', this.onSavedAddress)
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let res = await wx.wxp.request4({
      url: 'http://localhost:3000/user/my/address',
      method:'get'
    })
    let addressList = res.data.data 
    let selectedAddressId = addressList[0].id
    this.setData({
      addressList,
      selectedAddressId
    })
  },
})
{
  "usingComponents": {
    "van-cell": "@vant/weapp/cell/index",
    "van-cell-group": "@vant/weapp/cell-group/index",
    "van-icon": "@vant/weapp/icon/index",
    "van-radio": "@vant/weapp/radio/index",
    "van-radio-group": "@vant/weapp/radio-group/index",
    "van-button": "@vant/weapp/button/index",
    "mp-slideview": "weui-miniprogram/slideview/slideview"
  }
}
<!--miniprogram/pages/address-list/index.wxml-->
<!-- <text>miniprogram/pages/address-list/index.wxml</text> -->
<wxs module="fn">
  module.exports = {
    // 将数组合并为字符串
    join: function (arr) {
      return arr.join('')
    }
  }
</wxs>
<van-cell-group>
  <van-cell bind:click="getAddressFromWeixin" title="获取微信收货地址" is-link>
    <van-icon slot="icon" color="green" name="chat-o" style="margin-right:10px;" />
  </van-cell>
</van-cell-group>

<van-radio-group value="{{ selectedAddressId }}" bind:change="onChange">
  <van-cell-group title=" ">
    <block wx:for="{{addressList}}" wx:key="id">
      <mp-slideview data-id="{{item.id}}" buttons="{{slideButtons}}" bindbuttontap="onSlideButtonTap">
        <van-cell use-label-slot>
          <view slot="icon" class="vertical-align" style="margin-right:10px">
            <van-radio icon-size="16px" name="{{item.id}}"></van-radio>
          </view>
          <view slot="title">
            <view class="van-cell-text">{{item.userName}}{{item.telNumber}}</view>
          </view>
          <view slot="label">
            <view class="van-cell-text">收货地址:{{fn.join(item.region)}}{{item.detailInfo}}</view>
          </view>
          <van-icon data-id="{{item.id}}" bind:click="edit" slot="right-icon" name="edit" />

        </van-cell>
      </mp-slideview>
    </block>
  </van-cell-group>
</van-radio-group>

<view class="address-btns">
  <van-button bind:click="confirm" type="default" size="large">选择</van-button>
  <van-button custom-class="new-address" bind:click="navigateToNewAddressPage" type="primary" size="large">新增收货地址
  </van-button>
</view>
/* miniprogram/pages/address-list/index.wxss */
.vertical-align{
  display: flex;align-items: center;
}
.add-button{
  width:100%;
  position: fixed !important;
  bottom: 0;
}
page{
  height: 100%;
}

.address-btns{
  position: fixed !important;
  width: 690rpx;
  bottom: 0;
  margin: 30rpx;
}
.new-address{
  margin-top: 30rpx;
}

二、效果

显示全文