【问题标题】:how to add a string to the end of url with nuxt dynamic routing如何使用 nuxt 动态路由将字符串添加到 url 的末尾
【发布时间】:2020-09-29 12:50:20
【问题描述】:

出于 SEO 的目的,我想在动态路径的末尾添加一个字符串(产品标题、类别标题……)。 我的产品页面结构是这样的:

pages:

product (folder)
- _id.vue

所以为了显示产品单页,我使用 URL example.com/product/1 其中1 是产品 ID。 然后在 _id.vue 页面中获取我的产品:

async fetch(){
    let response = await this.axiosFetch(`product/${this.$route.params.id}`)
    if(this.resOk(response.status)){
        if(this.notEmpty(response.data)){
            this.product = response.data
        }
    }else{
        this.$nuxt.error({ statusCode: 404, message: "not found" })
    }
},

现在如上所述,我想在 url 末尾添加产品标题,例如 example.com/product/1/nike-shoe 我该怎么做??

更新

还有一个问题不能仅通过 url 上的参数来解决: 我有一个类别页面example.com/category。在页面获取我获取这样的猫(在页面上创建 catId 是 0 来获取父母并且每个父母我获取孩子):

async fetch(){
  let res = await this.$axios.$get(`category/${this.catId})
  this.catArray.push(res)
}

我从父 ID 中获取父级,获取子级并加载下面的父级等等。所有这些都在 example.com/category 中。没有路由更改仅将 catId 发送到路由查询(因此我可以使用 catId 从另一个页面导航)。那么如何在 url 末尾添加每个选定类别的标题并且仍然在同一页面中??

【问题讨论】:

  • 你试过this.$route.push吗?
  • product(folder)->_id(folder)->_slug.vue 怎么样?
  • @ma_jafari ,push 会改变路由并指向它,因为没有这样的页面它会给出 404
  • @Jazuly,我知道你在说什么。发送到该页面并获取我获取的第一个参数,对吗?如果有的话,我更喜欢其他可能的选择!

标签: vue.js vuejs2 nuxt.js vue-router


【解决方案1】:

您可以使用带有产品名称和末尾的id 的路由,并解析$route.params.id 以获取id。 为此,您需要使用slugify

您的路线将如下所示: example.com/product/${slugifiedProductName}-${id}

例如:example.com/product/nike-shoe-1

在文件pages/product/_id.vue 中使用正则表达式提取id

async fetch(){
    const id = this.$route.params.slug.match(/([0-9])+$/)[0]
    let response = await this.axiosFetch(`product/${id}`)
    if(this.resOk(response.status)){
        if(this.notEmpty(response.data)){
            this.product = response.data
        }
    }else{
        this.$nuxt.error({ statusCode: 404, message: "not found" })
    }
},

注意:如果使用 UUID,则正则表达式为 [0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$

【讨论】:

  • 很多。对于我用两个参数编码并获取第一个参数的产品。 /product/_id/_slug 。但我还有一个更复杂的问题!我用新问题更新了我的问题。
猜你喜欢
  • 2012-08-03
  • 2019-12-22
  • 2017-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多