【发布时间】:2019-06-26 14:30:45
【问题描述】:
我第一次使用Vue 并尝试将import 我当前的router 实例转换为JavaScript class,我在其中处理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 文件,我尝试将现有的router 实例导入并重用到push 和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 */
}
其背后的用例:我检查auth token 是否已过期。如果为真,我使用window.location.href 将我当前的href 保存在localStorage 中,并在再次登录时重定向到上一页。现在我正在尝试使用Router,因为重定向会闪烁,我希望使用 `Router 会更顺畅。
这是我的尝试,但都失败了。我可以在constructor 中记录Router,但在我的function 中始终是undefined。我不能在那里做push。有什么想法吗?
【问题讨论】:
-
该函数在类之外,因此无法访问该类。也许这就是问题所在。
-
@NielsLucas 我自己解决了这个问题:实际上,我的
Attempt 1是正确的方法,但我不必创建new Router()我可以将导入的分配给一个像这样的变量:const globalRouter = Router;,在我的函数中我可以这样做:globalRouter.push({ path: '/sample' });。这对我来说很好。 -
你为什么要在另一个变量中分配路由器。为什么不直接使用 Router.push() 呢?
-
@NielsLucas 如果是这样,那么
Router是未定义的。如果将其重新分配到变量中,它可以工作。我真的不知道为什么......上面的代码显示了我的文件的结构,所以没有别的,这可能会导致一些黑魔法...... -
这听起来很奇怪。但是我有一些场景,当我 console.log 它时,一些 import {SomeValue} 是未定义的,但是当我尝试在它上面使用函数时:SomeValue.someFunction(),一切都很好。你可能也是这种情况吗?告诉我。
标签: javascript vue.js import vue-router