vue.js 如何使用nuxt动态路由在url末尾添加字符串

oyt4ldly  于 7个月前  发布在  Vue.js
关注(0)|答案(2)|浏览(104)

为了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结尾我怎么能这样做??

更新

还有另一个问题,不能只通过URL上的参数来解决:我有一个类别页面example.com/category。在页面fetch上,我像这样获取猫(在页面create上,catId是0,以获取父母,并与每个父母一起获取孩子):

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


我获取父母,从父ID,获取孩子和加载below父等.所有这些都在example.com/category .没有路由更改只发送catId路由查询(所以我可以从另一个页面导航catId).所以我怎么能添加每个选定的类别的标题在url的末尾,仍然在同一个页面??

2mbi3lxu

2mbi3lxu1#

您可以使用一个带有产品的slugified名称和结尾的id的路由,并解析$route.params.id以获得id。为此,您需要使用slugify
您的路由看起来像:example.com/product/${slugifiedProductName}-${id}
例如:example.com/product/nike-shoe-1
在文件pages/product/_id.vue中,使用regexp提取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,则regexp为[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$

7uzetpgm

7uzetpgm2#

在nuxt 3中,事情更容易,像这样设置路由:pages/product/[id]/[category]/index.vue
然后在一个按钮或任何可点击的东西上添加:

<button @click="$router.push(`/product/${props.id}/${props.category}`)">View Porduct</button>

字符串
然后使用以下命令捕获该ID或类别:

<template>
  <div>{{ $route.params.id}} , {{ $route.params.category}}</div>
</template>


或者在脚本中使用:

<script setup lang="ts">
  const route = useRoute()
  const { id } = route.params()
  const { category } = route.params()  
</script>

相关问题