openId
openId是用戶在當前公眾號下的唯一標識(‘身份證’)又跛,就是說通過這個openId傲武,就能區(qū)分在這個公眾號下具體是哪個用戶币厕。
獲取openId思路
1.在項目路由守衛(wèi)中添加判斷甘畅,判斷當前緩存中是否有openId ; 沒有openId 跳轉(zhuǎn)到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與參數(shù)放入緩存
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 {
//生命周期函數(shù)
created() {
const code = getUrlKey("code"); // 截取code
if (!code) {
var domine = window.location.href.split("#")[0]; // 微信會自動識別# 并且清除#后面的內(nèi)容
// 如果沒有code埂蕊,說明用戶還沒授權(quán) 將當前地址傳遞給后臺
getAuthUrl({ url: domine }).then(res => {
window.location.href = res.data.data;
});
} else {
//如果有code,說明用戶點擊了授權(quán) 將獲取到的code傳遞給后臺
getUserInfo(code).then(res => {
res = res.data;
if (res.code === 0) {
// 返回狀態(tài)和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 路徑參數(shù)
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 參數(shù)
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null;
}
export {
GetUrlParame,
getUrlKey,
}