首页 > 解决方案 > (Vue路由器)在特定路线上推送参数

问题描述

我有一个组件,它具有基于外部数据的程序化路由。外部数据在组件中获取App.vue并在子组件中用作props.

数据在子组件中使用如下:

props: {
    externalData: Array
},
computed() {
    data() {
        return this.externalData
    }
}

这是我的router.js(摘录)

const routes = [
{
  path: "/:hae?",
  name: "Home",
  component: Home
},
{
  path: "*",
  name: "NotFound",
  component: NotFound
}
];

而我Home.vue$router.push方法(摘录):

created() {
  if (this.$route.path === "/") {
    this.$router.push({
      params: {
        hae: this.data[0].id
      }
    });
  }
},

所以这就是我想要实现的目标:

这是我的示例数组:[{hae: "hae001"}, {hae: "hae002"}, {hae: "hae003"} ...] 当您导航到https://website.com/我希望路由器将您重定向到作为数组的第一个元素的参数,但是如果您导航到数组中不存在的其他位置(例如/something)我想要路由器渲染我的NotFound.vue组件。

我错过了什么?

标签: vue.jsvue-router

解决方案



created() {
  const firstDataElementExists = this.data && this.data[0] && this.data[0].hae
  if (!firstDataElementExists) {
        this.$router.push('/404')
        return
  }

  const isRootPath = this.$route.path === '/'
  if (isRootPath) {
    this.$router.push(this.data[0].hae)
    return
  } 

  const pathIsInData = !!this.data.find(d => d.hae === p)
  if (!isRootPath && !pathIsInData) {
    this.$router.push('/404')
  }
}


推荐阅读