[英]How to create Nuxt dynamic routing without the ID in the URL
通常在 Nuxt 中為博客文章之類的東西創建動態路由時,我會做類似以下結構的事情。
頁面目錄
/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.