openId
openId是用户在当前公众号下的唯一标识(‘身份证’),就是说通过这个openId,就能区分在这个公众号下具体是哪个用户。
获取openId思路
1.在项目路由守卫中添加判断,判断当前缓存中是否有openId ; 没有openId 跳转到anth
2.在auth 界面 获取openId 并将openId存到缓存中
main.js 代码
router.beforeEach((to, from, next) => {
const openid = localStorage.getItem('openId');
if (!openid) {
if (to.path === '/auth') {
next()
} else {
if( to.path==='/'){
next('/auth')
return
}
localStorage.setItem('now_url',to.fullPath) //当前页url与参数放入缓存
next('/auth')
}
} else {
next()
}
})
auth.vue
<template></template>
<script>
import { getUrlKey } from "@/utils.js";
import { getAuthUrl, getUserInfo } from "@/serve.js";
const murl = "http://xxxx.xx";
const url = localStorage.getItem("now_url");
export default {
//生命周期函数
created() {
const code = getUrlKey("code"); // 截取code
if (!code) {
var domine = window.location.href.split("#")[0]; // 微信会自动识别# 并且清除#后面的内容
// 如果没有code,说明用户还没授权 将当前地址传递给后台
getAuthUrl({ url: domine }).then(res => {
window.location.href = res.data.data;
});
} else {
//如果有code,说明用户点击了授权 将获取到的code传递给后台
getUserInfo(code).then(res => {
res = res.data;
if (res.code === 0) {
// 返回状态和UId
if (res.data.openId) {
localStorage.setItem("openId", res.data.openId);
console.log('url',murl + "/#" + url)
window.location.replace(murl + "/#" + url);
}
}
});
}
},
data() {
return {};
},
methods: {
// 截取code
}
};
</script>
util.js
// 截取hash 路径参数
const GetUrlParame = (parameName) => {
const arr = (location.hash || '').split('?')[1] ? (location.hash || '').split('?')[1].split('&') : [];
let params = {}
for (var i = 0; i < arr.length; i++) {
const data = arr[i].split('=')
if (data.length === 2) {
params[data[0]] = data[1]
}
}
return params[parameName]
}
const getUrlKey = name => { //获取url 参数
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null;
}
export {
GetUrlParame,
getUrlKey,
}