前言
在电商系统中,收货地址是必不可少的功能,没有收货地址用户在下单就没法收到货,而且一个用户会有多个收货地址,比如寄给自己,或者寄给别人。一搬在收货地址选择中会有个默认收货地址以防止每次下单都要选择地址。
一、添加收货地址功能实现
<van-cell-group>
<van-field model:value="{{ userName }}" placeholder="收货人" clearable label="收货人" border="{{ false }}" />
<van-field model:value="{{ telNumber }}" type="number" placeholder="手机号或座机" clearable label="电话"
border="{{ false }}" />
<van-cell>
<view slot="title">
<picker bind:change="bindRegionChange" mode="region" value="{{region}}" custom-item="全部">
<view class="picker">
<text style="padding-right:55px;">省市区</text>
{{region[0]}},{{region[1]}},{{region[2]}}
</view>
</picker>
</view>
</van-cell>
<van-field model:value="{{ detailInfo }}" placeholder="详细地址" clearable label="详细地址" border="{{ false }}" />
</van-cell-group>
<view style="padding:20px 15px">
<van-button bind:click="save" type="primary" size="large">保存并使用</van-button>
</view>
{
"navigationBarTitleText": "收货地址",
"usingComponents": {
"van-field": "@vant/weapp/field/index",
"van-cell-group": "@vant/weapp/cell-group/index",
"van-cell": "@vant/weapp/cell/index",
"van-button": "@vant/weapp/button/index"
}
}
// miniprogram/pages/new-address/index.js
Page({
/**
* 页面的初始数据
*/
data: {
id:0,
userName:'',
telNumber:'',
region: ['广东省', '广州市', '海珠区'],
detailInfo:''
},
/**
* 保存地址
*/
async save(e){
// let data = this.data
let userName = this.data.userName
let telNumber = this.data.telNumber
let detailInfo = this.data.detailInfo
let region = this.data.region
let id = this.data.id
if (!userName || !telNumber || !detailInfo){
wx.showModal({
title: '数据项不能为空',
})
return
}
if (!/[\d-]{11,18}/.test(telNumber)){
wx.showModal({
title: '电话格式对吗?',
})
return
}
let data = {
userName,
telNumber,
detailInfo,
region,
id
}
let method = id ? 'put' : 'post'
let res = await wx.wxp.request4({
url:'http://localhost:3000/user/my/address',
method,
data
})
if (res.data.msg == 'ok'){
let opener = this.getOpenerEventChannel()
let address = this.data
if (!id) address.id = res.data.data.id
opener.emit("savedNewAddress", address)
wx.navigateBack({
delta: 1,
})
}else{
wx.showToast({
title: '添加失败,是否电话重复了?',
})
}
},
/**
* 省市区选择改变
*/
bindRegionChange: function (e) {
this.setData({
region: e.detail.value
})
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
let opener = this.getOpenerEventChannel()
opener.on("editAddress", address=>{
this.setData({
userName:address.userName,
telNumber:address.telNumber,
detailInfo:address.detailInfo,
region:address.region,
id:address.id
})
})
},
})