兼容ios和android获取地址
先在src下创建lib目录,里面创建address.js,代码如下所示:
import Axios from 'axios'
export default {
getWxInfo() {
// 请求参数
var data = {
host: location.href
}
Axios.post('/wechat/getConfig', data)
.then(res => {
console.log(res)
var appid = res.data.appid
let timestamp = res.data.timestamp
let nonceStr = res.data.nonce_str
let signature = res.data.sign
wx.config({
debug: false,
appId: appid,
timestamp: timestamp,
nonceStr: nonceStr,
signature: signature,
jsApiList: [
'checkJsApi',
'openAddress'
]
})
})
},
// 判断返回手机是否为ios
isIOS() {
let isIphone = navigator.userAgent.includes('iPhone')
let isIpad = navigator.userAgent.includes('iPad')
return isIphone || isIpad
}
}
因为ios获取收货地址只有在首页的时候才会有作用,所以可以在main.js或router.js通过路由守卫来判断跳到首页时调用getWxInfo获取appid、timestamp、nonce_str、sign来config注册事件
import wechat from './lib/address'
router.beforeEach((to, from, next) => {
if (wechat.isIOS()) {
if (from.path === '/') {
wechat.getWxInfo() //调用方法
}
}
})
接着就是要在address.vue获取地址
address.vue页面上一段未获取的和获取回来的标签(通过v-if 、v-else来判断flag的值)
// 未获取回来显示
<div class='address' v-if='flag' @click="Address">
<img src="" alt=""><span>请填写收货地址</span>
</div>
// 获取回来显示
<div class='address has' v-else>
<dl>
<dt><img src="" alt=""></dt>
<dd>
<p><span>{{addressInfo.userName}}</span><span>{{addressInfo.telNumber}}</span></p >
<p>{{addressInfo.provinceName}}{{addressInfo.cityName}}{{addressInfo.countyName}}{{addressInfo.detailInfo}}</p >
</dd>
</dl>
</div>
address.vue 里面js这样写
import wechat from '@/lib/address'
export default {
data(){
return{
flag:true,
addressInfo:{} //保存收货地址信息
}
},
mounted(){
// android 下在再去注册事件
if (!wechat.isIOS()) {
wechat.getWxInfo() //调用方法
}
},
methods:{
// 用户选择收货地址
Address() {
var that = this
wx.openAddress({
success: function (res) {
console.log(res);
that.addressInfo = {
'userName': res.userName,
'telNumber': res.telNumber,
'provinceName': res.provinceName,
'cityName': res.cityName,
'countyName': res.countryName,
'detailInfo': res.detailInfo,
'postalCode': res.postalCode
}
that.flag = false
},
fail: function (err) {
console.log(JSON.stringify(err))
console.info('获取收货地址失败')
that.flag = true
}
})
},
}
}
网友评论