关于vue-router做登录权限的思考

现在问题是 用 router-beforeEach来判断是否登录,当走login.vue时,异步请求结果,等结果回来后,存放到vuex中,并跳转.但跳到/时,总是获取不到 isLogin,哦自己写错变量了?

index.js

const router = new Router({
  // mode: 'history',
  routes: [
    // {
    //   path: '/',
    //   redirect: '/login'
    // },
    {
      path: '/login',
      component: resolve => require(['../components/login.vue'], resolve)
    },
    {
        path: '/',
        component: resolve => require(['../components/Home.vue'],resolve),
        children: [
            {
                path: '',
                component: resolve => require(['../common/admin.vue'],resolve)
            }
        ]
    }
  ]
})

main.js

// state 存放数据
// actions 触发 异步操作
// mutations 触发同步 操作
// geterrs 获取state
// modules 获取 

var store = new Vuex.Store({
    state: {
        userInfo: {
            name: '',
            id: "",
            phone: ''
        }
    },
    actions: {
        LOAD_USER_OUTHA(state,params) {
            console.log(state)
            axios.post('http://space.it-weyoung.com/admin/oauth/token',{
                grant_type: "password",
                client_id: 3,
                client_secret: "ZffWIz4NSsXqLTVgQdGH6awogIEKm7vymkS3dHFX",
                username: params.name,
                password: params.pass
            }).then((response) => {
                let data = response.data;
                console.log(data)
                if(data.access_token){
                    state.commit('SET_PROJECT_LIST',{
                        access_token: data.access_token,
                        token_type: data.token_type,
                        isLogin: true
                    });
                    window.localStorage.setItem("isLogin",true)
                }
            })
        }
    },
    mutations: {
        SET_PROJECT_LIST: (state,params) => {
            state.token = params.access_token;
            state.type = params.token_type;
            state.isLogin = params.isLogin;
        }
    },
    getters: {
        isLogin: state => {
            return state.isLogin; // 这一句写错了
                        return state.userInfo.isLogin 就可以了
        },
        token: state => {
            return state.token;
        },
        token_type: state => {
            return state.token
        }
    },
    modules: {

    }
});

/* eslint-disable no-new */
var vm = new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

// router.beforeEach((to, from, next) => {
//  var isLogin = router.app.$store.getters.isLogin;
//  console.log(router.app.$store)
//  if(!isLogin){ // 未登录时
//      console.log("未登录",isLogin)
//    if (to.path !== '/login') { // 路径不等于 login
//        return next({path: '/login'}); // 跳到 login
//    }else {
//        next(); // 路径等于 login 就跳转到 login
//    }
//  }else{
//      console.log("登录",isLogin)
//      if (to.path === '/login') {
//        return next({path: '/'});
//    }
//    next();
//  }
// })

你可能感兴趣的:(关于vue-router做登录权限的思考)