【问题标题】:(Vue Router) Push params when on a certain route(Vue路由器)在特定路线上推送参数
【发布时间】:2020-07-19 12:32:41
【问题描述】:

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


    【解决方案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')
      }
    }
    
    

    【讨论】:

    • 谢谢,它解决了参数的问题!对 NotFound 组件有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 2019-07-24
    • 2023-02-14
    相关资源
    最近更新 更多