Javascript Vue 路由器如何在页面加载时获取延迟加载模块的当前路由路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47170533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can Vue router get current route path of lazy-loaded modules on page load?
提问by Valorad
I have a vue app with router set up like:
我有一个带有路由器的 vue 应用程序,如下所示:
import index from './components/index.vue';
import http404 from './components/http404.vue';
// module lazy-loading
const panda= () => import(/* webpackChunkName: "group-panda" */ "./components/panda/panda.vue");
// ...
export const appRoute = [
{
path: "",
name: "root",
redirect: '/index'
},
{
path: "/index",
name: "index",
component: index
},
{
path: "/panda",
name: "panda",
component: panda
},
//...
{
path: "**",
name: "http404",
component: http404
}
];
So the panda module is lazy-loaded. However, when I navigate to pandapage, a console.log() of this.$route.pathin App.vue's mounted()lifecycle only outputs
所以panda模块是延迟加载的。然而,当我导航到panda的页面,一个的console.log()this.$route.path中App.vue的mounted()生命周期仅输出
"/"
“/”
instead of
代替
"/panda"
“/熊猫”
But index page works well, it shows exactly
但是索引页面运行良好,它显示准确
"/index"
“/指数”
as expected.
正如预期的那样。
So how can Vue router get current path correctly of a lazy-loaded page, when page is initially loaded? Did I miss something?
那么,当页面最初加载时,Vue 路由器如何正确获取延迟加载页面的当前路径?我错过了什么?
Edit:
编辑:
It can, however, catch the correct path after Webpack hot-reloads. It catches "/" on first visit of panda, but after I change something in source code, webpack-dev-server hot-reloads, then it gets "/panda".
但是,它可以在 Webpack 热重载后捕获正确的路径。它在第一次访问 时捕获“/” panda,但是在我更改源代码中的某些内容后,webpack-dev-server 热重载,然后它会得到“/panda”。
So I guess it has something to do with Vue life-cycle.
所以我想这与 Vue 生命周期有关。
回答by Andre
There is a currentRouteproperty that worked for me: this.$router.currentRoute
有一个currentRoute属性对我有用:this.$router.currentRoute
回答by Niklesh Raut
May be you need to use $routenot $router
可能你需要使用$routenot$router
check here : https://jsfiddle.net/nikleshraut/chyLjpv0/19/
在这里查看:https: //jsfiddle.net/nikleshraut/chyLjpv0/19/
You can also do it by $routerthis way
你也可以通过$router这种方式
回答by Nuno Ribeiro
Use this.$route.path.
Simple and effective.
使用this.$route.path. 简单有效。
回答by Vishal Vaghasiya
Hide Header in some components using the current route path.
使用当前路由路径隐藏某些组件中的 Header。
get current route path using
this.$route.path
使用获取当前路线路径
this.$route.path
<navigation v-if="showNavigation"></navigation>
data() {
this.$route.path === '/' ? this.showNavigation = false : this.showNavigation = true
}

