如何在另一个文件中使用vue router?
How to use the vue router in another file?
vue-router 运行良好,但我们想在另一个文件中推送路由。一些代码来澄清:
// src/router/index.ts
import { route } from 'quasar/wrappers'
import VueRouter from 'vue-router'
import routes from './routes'
export default route(function ({ Vue }) {
Vue.use(VueRouter)
const Router = new VueRouter({
scrollBehavior: () => ({ x: 0, y: 0 }),
routes,
mode: process.env.VUE_ROUTER_MODE,
base: process.env.VUE_ROUTER_BASE,
})
return Router
})
如果能够像这样在另一个文件中调整路线那就太好了:
// src/services/auth/authService.ts
import router from 'src/router'
if (router.currentRoute.path === '/login') {
console.log('authService push to /');
router.push('/')
}
但这会引发错误:
TS2339: Property 'currentRoute' does not exist on type 'RouteCallback'.
我们可能 exporting/importing 路由器不正确。
您可以使用docs建议的路线。
this.$route.path
路由将为您提供路由器的活动实例。
通过正确导出 Router
修复了它:
import { route } from 'quasar/wrappers'
import VueRouter from 'vue-router'
import routes from './routes'
export const Router = new VueRouter({
scrollBehavior: () => ({ x: 0, y: 0 }),
routes,
mode: process.env.VUE_ROUTER_MODE,
base: process.env.VUE_ROUTER_BASE,
})
export default route(function ({ Vue }) {
Vue.use(VueRouter)
return Router
})
然后在没有 this
上下文的 Vue 之外使用它,如下所示:
import { Router } from 'src/router'
if (Router.currentRoute.path === '/login') {
console.log('authService push to /')
Router.push('/')
}
希望这可以帮助其他人 运行 解决同样的问题。
vue-router 运行良好,但我们想在另一个文件中推送路由。一些代码来澄清:
// src/router/index.ts
import { route } from 'quasar/wrappers'
import VueRouter from 'vue-router'
import routes from './routes'
export default route(function ({ Vue }) {
Vue.use(VueRouter)
const Router = new VueRouter({
scrollBehavior: () => ({ x: 0, y: 0 }),
routes,
mode: process.env.VUE_ROUTER_MODE,
base: process.env.VUE_ROUTER_BASE,
})
return Router
})
如果能够像这样在另一个文件中调整路线那就太好了:
// src/services/auth/authService.ts
import router from 'src/router'
if (router.currentRoute.path === '/login') {
console.log('authService push to /');
router.push('/')
}
但这会引发错误:
TS2339: Property 'currentRoute' does not exist on type 'RouteCallback'.
我们可能 exporting/importing 路由器不正确。
您可以使用docs建议的路线。
this.$route.path
路由将为您提供路由器的活动实例。
通过正确导出 Router
修复了它:
import { route } from 'quasar/wrappers'
import VueRouter from 'vue-router'
import routes from './routes'
export const Router = new VueRouter({
scrollBehavior: () => ({ x: 0, y: 0 }),
routes,
mode: process.env.VUE_ROUTER_MODE,
base: process.env.VUE_ROUTER_BASE,
})
export default route(function ({ Vue }) {
Vue.use(VueRouter)
return Router
})
然后在没有 this
上下文的 Vue 之外使用它,如下所示:
import { Router } from 'src/router'
if (Router.currentRoute.path === '/login') {
console.log('authService push to /')
Router.push('/')
}
希望这可以帮助其他人 运行 解决同样的问题。