【问题标题】:this.$route.name is getting as null in vue routerthis.$route.name 在 vue 路由器中为空
【发布时间】:2019-12-02 20:58:31
【问题描述】:
<template>
  <router-link :to="{ name: 'work', params: { projectId: $store.state.projectId }}">Work</router-link>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component()
export default class NavBar extends Vue {

  public activeIndex: string;

  public mounted() {
    // TODO: Below name is getting as null
    this.activeIndex = this.$route.name;
  }
}
</script>

我的路由器定义如下。

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
    },
    {
      path: '/work/project/:projectId',
      name: 'work',
      component: () => import('./views/Work.vue'),
    },
  ],
});

当我在浏览器中点击以下网址时,我得到 'this.$route.name' 作为 'home'

https://localhost/

当我在浏览器中点击以下网址时,我得到 this.$route.name 为空。

https://localhost/work/project/38

那么,当我点击上面的 url 时,我没有像 this.$route.name 一样得到“工作”,这是怎么回事?

console.log(this.$route) 的输出;

fullPath: "/"
hash: ""
matched: []
meta: {}
name: null
params: {}
path: "/"
query: {}

【问题讨论】:

  • console.log(this.$route) 在该对象中显示什么?
  • 添加有问题
  • 这可能是因为/work/project 与/work/project/:projectId 模式不完全匹配,因为缺少projectId 部分。如果您希望参数是可选的,请进行以下更改 /work/project/:projectId -> /work/project/:projectId?。
  • 我提供了参数'38'

标签: html vue.js vuejs2 vue-router


【解决方案1】:

到目前为止,我能够进行以下管理。仍然有更好的答案。

public created() {
    const unwatch = this.$watch(
      () => this.$route,
      (route, prevRoute) => {
        this.activeIndex = route.name;
        unwatch();
      });
  }

【讨论】:

    【解决方案2】:

    Home 和 Work 路由的区别在于组件的延迟加载。 'home' 组件不像'work' 那样延迟加载。如果在调用挂载之前未加载组件,将导致您获得空值。为了克服这个问题,您可以将“工作”组件加载为急切加载。但请注意,这可能会增加捆绑包的大小。见https://router.vuejs.org/guide/advanced/lazy-loading.html

        import Work from "./views/Work.vue";
        const router = new Router({
                                   mode: 'history',
                                   base: process.env.BASE_URL,
                                   routes: [
                                    {
                                       path: '/',
                                       name: 'home',
                                       component: Home,
                                    },
                                    {
                                       path: '/work/project/:projectId',
                                       name: 'work',
                                       component: Work,
                                    },
                                  ],
                              });
    

    【讨论】:

    • 我确实意识到急切加载可能并不总是可取的。在延迟加载的情况下,@Anonymous Creator 的答案应该是被接受的。
    猜你喜欢
    • 2017-01-20
    • 1970-01-01
    • 2021-12-26
    • 2021-08-07
    • 2019-09-02
    • 2020-01-13
    • 2018-02-10
    • 2018-11-23
    • 2021-10-30
    相关资源
    最近更新 更多