Vue:在助手类中导入路由器并推送路由

时间:2019-06-26 14:30:45

标签: javascript vue.js import vue-router

我第一次使用Vue,并尝试将当前的import实例router移至JavaScript class的地方,我在其中处理{ {1}}。

这是我的Authentification文件:

router

这是我的帮助器import Vue from 'vue'; import Router from 'vue-router'; import FirstRoute from '@/components/FirstRoute'; import SecondRoute from '@/components/SecondRoute'; Vue.use(Router); export default new Router({ mode: 'history', scrollBehavior() { return { x: 0, y: 0 }; }, routes: [ { path: '/', meta: { requiredAuth: false }, name: 'FirstRoute', component: FirstRoute, }, { path: '/second', meta: { requiredAuth: false }, name: 'SecondRoute', component: SecondRoute, }, ], }); 文件,在这里我尝试导入并重用现有的class实例,以routerpush中的route

function

其用例:我检查import Router from '../router'; /* This is where I import the router instance */ const globalRouter = new Router(); /* Attempt 1 */ class AuthService { constructor() { console.log(Router); /* This console.log() shows me my router instance with all routes - so it was imported the right way and works */ const routerInClass = new Router(); /* Attempt 2 */ this.doSomething(); } } doSomething() { const routerInFunction = new Router(); /* Attempt 3 */ /* Results of my attempts: */ console.log(globalRouter); /* Result Attempt 1: undefined */ console.log(routerInClass); /* Result Attempt 2: undefined */ console.log(routerInFunction); /* Result Attempt 3: undefined */ console.log(Router); /* Result Attempt 4: undefined */ /* Use imported router to push a route */ Router.push({ path: '/SecondRoute' }); /* Not working with attempt 1 to 4 */ } 是否过期。如果为true,则在auth token中使用href保存当前的window.location.href,并再次登录时,重定向到上一页。现在,我正在尝试使用localStorage,因为重定向会闪烁,并且我希望它能与`Router一起使用。

这是我的尝试,都失败了。我可以在Router中登录Router,但是在我的constructor中,它始终是function。我无法在此处执行undefined。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

在您的帮助文件中,您无需导入Vue或VueRouter

import router from '../router';

class AuthService {
    constructor() {
        console.log(router);
        this.doSomething();
    }

    doSomething() {
        /* Use imported router to push a route */
        router.push({ path: '/SecondRoute' });
    }
}

编辑:在您的课程中移动doSomething函数