1、app.vue
<script>
export default {
onLaunch: function() {
var token = uni.getStorageSync('token');
if (token) {
this.$isResolve();
} else {
// 公众号授权登录
this.getCode();
}
},
methods: {
// 公众号授权登录
getCode() {
var _this = this;
let link = window.location.href;
console.log("==获取当前页面的链接==")
console.log(link);
// 截取code
var code = _this.getUrlCode().code;
// 如果有code就去登录,获取token;没有的话,跳转微信授权链接去获取
if (code) {
// 使用登录接口用code获取token
uni.$u.http.get('/api/xxx/login', {
params: {
code: code,
}
}).then(res => {
console.log("==登录成功==");
console.log(res);
_this.$isResolve();
// 缓存token
uni.setStorageSync('token', res.data.token);
})
} else {
let appid = _this.$appid; // 微信公众号id
let uri = encodeURIComponent(link);
let authURL =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
window.location.href = authURL;
}
},
// 截取url中的code
getUrlCode() {
var _this = this;
var url = location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
var strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
}
}
// console.log(theRequest);
return theRequest;
},
}
}
</script>
二、main.js
import Vue from 'vue'
import App from './App'
// 引入配置文件
import config from '@/config/config.js'
Vue.prototype.$baseUrl = config.baseUrl;
Vue.prototype.$appid = config.appid; // 开发者id
// 解决地图跨域
import {VueJsonp} from 'vue-jsonp'
Vue.use(VueJsonp)
// 回调
Vue.prototype.$onLaunched = new Promise(resolve => {
Vue.prototype.$isResolve = resolve;
})
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
三、h5跨域问题
打开manifest.json文件,左侧菜单,最下面的【源码视图】。
"h5" : {
"publicPath" : "./",
"devServer" : {
"https" : true,
"disableHostCheck" : true,
"port" : 8080,
"proxy" : {
"/" : {
"target" : "网站域名",
"changeOrigin" : true,
"secure" : false,
"pathRewrite" : {
"^/" : ""
}
}
}
},
"sdkConfigs" : {
"maps" : {
"qqmap" : {
"key" : "腾讯地图key"
}
}
},
"template" : "",
"router" : {
"mode" : "hash",
"base" : "/h5"
},
"domain" : "网站域名",
"title" : "网站标题",
"optimization" : {
"treeShaking" : {
"enable" : false
}
}
},