(Vue路由器)在特定路线上时推送参数

时间:2020-07-19 12:32:41

标签: vue.js vue-router

我有一个组件,该组件具有基于外部数据的程序化路由。 外部数据在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组件。

我想念什么?

1 个答案:

答案 0 :(得分:1)


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')
  }
}