繁体   English   中英

如何在 URL 中创建没有 ID 的 Nuxt 动态路由

[英]How to create Nuxt dynamic routing without the ID in the URL

通常在 Nuxt 中为博客文章之类的东西创建动态路由时,我会做类似以下结构的事情。

页面目录

  • 页面/帖子/
  • 页面/帖子/index.vue
  • 页面/帖子/_category/
  • 页面/帖子/_category/index.vue
  • 页面/帖子/_category/_sub-category/
  • 页面/帖子/_category/_sub-category/_id.vue

/pages/posts/_category/_sub-category/_id.vue

<template>
  <div>
    <h1>{{ title }}</h1>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data () {
    return {
      id: this.$route.params.id,
      all_posts: '',
      filtered_post: '',
      post_data: '',
      category: '',
      sub_category: '',
      title: ''
    }
  },

  mounted () {
    this.getSingle()
  },

  methods: {

    getSingle () {
      axios.get('someapiendpoint')
        .then((response) => {
          // get response data
          this.all_posts = response.data
          // filter response data by id
          this.filtered_post = this.all_posts.filter(post => post.id === this.id)
          // get data from index [0]
          this.post_data = this.filtered_post[0]
          // set data vars
          this.category = this.post_data.category
          this.sub_category = this.post_data.sub_category
          this.title = this.post_data.title
        })
    }

  }

}
</script>

Nuxt.config.js

generate: {
    routes () {
      return axios.get('https://someapiendpoint').then((res) => {
        return res.data.map((post) => {
          return {
            route: '/posts/' + post.category + '/' + post.slug + '/' + post.id,
            payload: (post)
          }
        })
      })
    }
  },

Nuxt 链接

<nuxt-link :to="{ path: '/posts/' + post.category + '/' + post.sub_category + '/' + post.id}" v-for="post in displayedPosts" :key="post.id">
    {{ post.title }}
</nuxt-link>

这会产生类似的路线

/posts/my-category/my-sub-category/my-article-title/12345

我的问题是如何从 URL 中删除 ID 并仍然根据 ID 获取数据但使用这样的 URL

/posts/我的类别/我的子类别/我的文章标题/

在 URL 上保留 id 对 SEO 来说并不是很好。 您只能通过 slug 而不是 ID 过滤帖子,每个帖子的 slug 都是唯一的。 或者如果你仍然想使用 ID 作为过滤的 key,你可以使用 Vuex 在点击时保存当前的帖子 ID。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM