Vue Router 在首页获取 fullPath 一直都是 '/' ?

2019-10-28 14:54:58 +08:00
 nyse
// src/main.js

var app = new Vue({
  el: '#app',
  router,
  store,
  ...App,
  created: function() {
    console.log(router);
    
    router.push({
      path: '/init',
      query: {
          redirect: router.currentRoute.fullPath
          // 进入页面时,先统一转跳到 init 页面进行初始化(判断登录状态)
          // 附上当前 fullPath 用于初始化完成后转跳回来
      }
    });
  }
});

为什么在 main.js 中,通过 router.currentRoute.fullPaththis.$route.fullPath 后去到的地址都是 '/' ?

3557 次点击
所在节点    问与答
12 条回复
daguaochengtang
2019-10-28 16:35:39 +08:00
要实现你说的需求应该放在路由守卫里来做
```
router.beforeEach(async (to, from, next) => {
const fullPath = to.fullPath
next({
path: '/init',
query: {
redirect: encodeURIComponent(fullPath)
}
})
})
```
nyse
2019-10-28 16:53:21 +08:00
@nikolausliu #1 这个我知道,但是这样的话每次转跳都会被拦截到要怎么处理?
jeodeng
2019-10-28 16:56:28 +08:00
@nyse 你的要求不就是都被拦截吗?统一进入 init 页面再跳转
nyse
2019-10-28 17:01:28 +08:00
@jeodeng #3 我说的是首次进来,后面在 APP 中转跳当然不用啦
learnshare
2019-10-28 17:01:58 +08:00
@jeodeng 判断是否登录不能跳页面,用 #1 的方法处理
只有未登录的状况需要跳到登录页面,顺便带上需要跳回的 URL,登录后跳回来
nyse
2019-10-28 19:29:57 +08:00
@learnshare #5 好像也只能这样,这样的话就每次转跳前做判断,感觉不是很完美。

就是不知道有没有哪个地方可以实现第一次进入就执行一次。
agdhole
2019-10-28 19:35:28 +08:00
@nyse #6 存到 localstorage 判断是否是第一次就行了
nyse
2019-10-28 21:46:37 +08:00
@agdhole #7 关键就是用来 beforeEach 这个钩子,每次转跳都会触发,感觉不是很合理


虽然性能也没啥影响
markzyh
2019-10-28 21:58:33 +08:00
路由守卫,根据 from 判断是否是第一次
learnshare
2019-10-28 22:16:45 +08:00
@nyse 每次跳转都检查才对,因为你也不知道用户以哪个页面作为入口
daguaochengtang
2019-10-29 14:36:05 +08:00
关于“为什么在 main.js 中,通过 router.currentRoute.fullPath 或 this.$route.fullPath 后去到的地址都是 '/' ?”
因为 created 的时候,“路由还没有挂载,打印的是根路由”。我这个说法可能不是很准确,明白这么个意思就行。你可以试下下面的代码:
```
created: function() {
console.log(router.currentRoute.fullPath)
setTimeout(() => {
console.log(router.currentRoute.fullPath)
}, 2000)
}
```
第一个打印的是“/”,第二个打印的是当前页面的实际路由。所以你可以在这个 created 里做一个轮询来判断,但是我还是觉得用 beforeEach 更规范一点
nyse
2019-10-29 19:28:31 +08:00
@nikolausliu #11 是的,这个我有试过

目前的情况就是希望在生命周期有某个环节,当首次进入的时候执行一次最好了。

因为轮询和 beforeEach 感觉都不是很优雅,虽然性能基本没影响。

我目前是在 beforeEach 处理的。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/613670

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX