一、新建public.js文件
在common目录下新建一个public.js文件,完整代码如下
export function getLocationInfo(a = "scope.userLocation") {
// 获取定位授权
function getAuthorizeInfo() {
return new Promise((resolve, reject) => {
uni.authorize({
scope: a,
success() {
resolve();
},
fail() {
reject();
}
});
});
}
// 查看是否已经授权定位
function isGetLocation() {
return new Promise((resolve, reject) => {
console.log('查看是否已经授权定位')
// #ifdef MP
uni.getSetting({
success(res) {
if (!res.authSetting[a]) {
console.log('没有授权,获取授权')
// 没有授权,获取授权
getAuthorizeInfo().then(() => {
resolve();
}).catch(() => {
reject();
});
} else {
console.log('已授权,获取地理位置信息')
// 已授权,获取地理位置信息
uni.getLocation({
type: 'wgs84', //返回可以用于uni.openLocation的经纬度
geocode: true,
success: (res) => {
// 成功获取地理位置信息后调用接口
callApi(res).then(() => {
resolve(res);
}).catch(() => {
reject();
});
},
fail: () => {
reject();
}
});
}
}
});
// #endif
});
}
// 调用查看是否已经授权定位,获取地理位置信息
return isGetLocation();
}
// 调用接口的方法
function callApi(locationInfo) {
return new Promise((resolve, reject) => {
// 调用接口
// TODO: 在此处添加您的接口调用代码
});
}
//一定要声明暴露函数,可以被引用
module.exports = {
getLocationInfo
}
二、挂载到全局
//main.js
import wsRequest from "@/common/public.js"
//挂载到全局
Vue.prototype.$public=$public
三、在页面中调用
this.$public.getLocationInfo()