微信公众号vue项目路由配置

vue yekong 1464℃

当我们配置好vue项目可以本地调试后,还需要配置路由文件,因为公众号需要授权,所以打开页面后需要先跳转到公众号页面去授权,获取授权后携带code再回跳回来.
这就需要我们做一个判断是否已经授权过了。
我们需要在路由跳转前做一个判断是否有用户信息,没有的话就跳转到公众号页面取授权获取code传到我们的接口获取用户信息保存到本地。
当再次进入这个页面的时候 如果有用户信息标识已经授权过了,无须再次进入授权页面.

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import api from '@/config/config';
import {wxLogin} from '@/utils/api'
import store from 'xr-storage'

Vue.use(VueRouter)

//从url中获取参数值
function getval(url: any, name: any) {
    const reg = new RegExp("(^|\\?|&)" + name + "=([^&|#]*)(\\s|&|#|$)", "i");  // 因为vue有添加“#”的特点,所以这里的正则表达式会匹配 & -- &/#
    if (reg.test(url)) return unescape(RegExp.$2.replace(/\+/g, " "));
    return "";
}

function getcode(to: any, from: any, next: any) {
    const locationUrl = window.location.href;
    const userInfo = store({method: 'get', key: 'memId'}) ? store({method: 'get', key: 'memId'}) : '';
    if (!userInfo) {  // 内存内没有openid
        if (locationUrl.indexOf("code") >= 0) {  // 链接里有code
            wxLogin({code: getval(locationUrl, 'code')}).then(function (res: any) {
                if (res.Status == '1') {
                    store({method: 'set', key: 'memId', value: res.Result.memId})
                    next();
                } 
            })
        } else {  // 链接里没有code
            store({method: 'set', key: 'url', value: to.fullPath.toString()});
            // window.localStorage.setItem("url", to.fullPath);
            const url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + api.appId + "&redirect_uri=" + api.redirectUri + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
            window.location.href = url;
        }
    } else {
        next();
    }
}


const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location: any) {
    // @ts-ignore
    return originalPush.call(this, location).catch(err => err);
};
router.beforeEach(async (to, from, next) => {
    if (to.meta.title) {
        document.title = to.meta.title;
    }
    await getcode(to, from, next);
})

router.afterEach(() => {
    window.scrollTo(0, 0);
})
export default router

喜欢 (2)