鍍金池/ 問答/HTML/ VueRouter的全局守衛(wèi),如何獲取到Vue實(shí)例

VueRouter的全局守衛(wèi),如何獲取到Vue實(shí)例

其實(shí)我想在beforeEach這個鉤子函數(shù)里面做登錄驗(yàn)證,而這個登錄驗(yàn)證會調(diào)后臺接口,但是這個鉤子函數(shù)里面獲取不到vm的實(shí)例,這樣我就無法取得store里的token,也無法請求后臺,折騰了一早上,實(shí)在沒找到解決方法,只能請求大家指點(diǎn)一二

相關(guān)代碼

Router.vue
<script>
    import Vue from 'vue'
    import VueRouter from 'vue-router'
    Vue.use(VueRouter)
    import Api from '@/components/config/Api'
    import home from '@/pages/index'
    import login from '@/pages/login'
    import info from '@/pages/info'

    const router = new VueRouter({
        routes: [{
            path: '/',
            name: 'index',
            component: home
        },{
            path: '/login',
            name: 'login',
            component: login
        },{
            path: '/info',
            name: 'info',
            component: info
        }],  
    });
    
    router.beforeEach((from, to, next) => {
        this.$http.get(Api.is_login_uri,{params: {"1":this.$store.state.token}}).then(function(res){
            let code = res.data.code;
            if(code != "0"){
                next({path:'/info',params:{"msg":res.data.data}});
            }
        },function(error){
            next({path:'/info',params:{"msg":"請求驗(yàn)證登錄出了問題"}});
        });
    })

    export default router;
</script>
main.js的代碼
import router from './components/config/Router'
import store from './components/config/Store'

// 導(dǎo)入 pages 下的 Home.vue 
//import index from './pages/index'

// 創(chuàng)建 Vue 實(shí)例*
var vm = new Vue({
  el: '#app',
  router,
  store,
  data(){
    return {
    }
  },
  created(){
    document.title=this.Global.appName;
  }
})
回答
編輯回答
陪她鬧

你在路由router.js里引入你的store.js試試哦

2018年8月27日 12:59
編輯回答
萌小萌

換個思路,在 router.js 里面把 store 引進(jìn)去,不就行了?

2017年3月20日 04:25