如何在VueJs中按路线名称获取特定路线数据?

时间:2019-10-04 11:26:10

标签: javascript vue.js vuejs2 vuex vue-router

在VueJs中,我始终可以访问当前路线数据。但是,如果我想通过名称访问另一条路线的数据怎么办? 假设我已定义路线,

[
    {
        name: "dashboard",
        path: "/",
        component: Dashboard,
        meta: {
            title: "Dashboard",
        }
    },
    {
        name: "login",
        path: "/login",
        component: Login,
        meta: {
            title: "Login",
        }
    }
]

现在假设我正在仪表板路线中。我可以通过this.$route访问其数据,但是如果我要访问名为login的路由的元数据怎么办? 是否有任何函数可以将名为login的路由的对象返回给我?

2 个答案:

答案 0 :(得分:1)

您可以使用resolve方法将路线名称转换为这样的路径:

const { href } = this.$router.resolve({
  name: 'password-change',
});

或者如果您需要更多信息:

const { route } = this.$router.resolve({
  name: 'password-change',
});

作为回报,您将获得一个包含路径,元数据,参数等的对象。

答案 1 :(得分:0)

您可以使用this。$ router

访问路线。
this.$router.options.routes[0].meta

当然,您必须掌握正确的路线


更新

您当然可以遍历数组:

getRoute: function (routeName) {
  let result = this.$router.options.routes.find(i => i.name === routeName)
  if (result == null) {
    this.$router.options.routes.forEach(element => {
      if (element.children) {
        let route = element.children.find(i => i.name === routeName)
        if (route != null) {
          result = route
        }
      }
    })
  }
  return result
},