如何使用nuxt动态路由将字符串添加到url的末尾

时间:2020-09-29 12:50:20

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

出于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" })
    }
},

现在如上所述,我想在网址末尾添加产品标题,例如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的末尾添加每个选定类别的标题,并且仍然位于同一页面?

1 个答案:

答案 0 :(得分: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}$