我正在构建一个简单的Nuxt JS博客,其中包含一个包含一系列博客文章的blog.json
文件,其中包含:
我将很快附上这个格式。我知道如何迭代每个数组项并在页面上显示它,我也对dynamic routing in Nuxt JS有基本的了解和一些基本经验。
我目前面临的问题是我需要能够访问单个数组项并将它们用作博客帖子,例如:pages/blog/_slug
其中_slug
将成为博客文章的标题,连字符+全部小写自动。
我想知道如何访问我的示例中的Winter博客文章,并能够使用以下JSON格式访问mysite.com/blog/winter-blog-post
:
{
"blogs": [
{
"title": "Summer blog post",
"body": "<div class=\"post\">My blog content</div>",
"created": "2019-03-14 10:08:00"
}
{
"title": "Winter blog post",
"body": "<div class=\"post\">My blog content</div>",
"created": "2019-03-15 10:08:00"
},
{
"title": "Spring blog post",
"body": "<div class=\"post\">My blog content</div>",
"created": "2019-03-16 10:08:00"
}
]
}
我本质上希望能够访问mysite.com/blog/winter-blog-post
并让它使用该特定数组项的内容。
我假设你的页面设置正确,你可以达到/blog/_slug
,所以它只需要传递所需的参数并根据需要进行转换。在blog.vue中,您将拥有一个帖子列表,点击某些内容会导航到完整的文章。该click事件将触发一个方法,您可以在其中操作标题并将其用作参数。因此,如果您有一个“阅读更多...”按钮,您可以将@click="readMore(blog.title)"
分配给该按钮。
然后在您的方法中,您可以获取传递的'title'参数,根据需要进行更改,然后触发路径更改。
methods: {
readeMore(title) {
let passedTitle = title.toLowerCase()
passedTitle = passedTitle.replace(" ", "-")
this.$router.push('/blog/' + passedTitle)
}
}
然后在你的_slug.vue中你接受传递的参数,将其更改回来并使用它来查找你的文章。
export default {
asyncData({params, $axios }) {
let title = params.passedTitle.replace("-", " ")
let oldTitle = title.charAt(0).toUpperCase() + title.slice(1)
// make your query however you do, if with axios...
$axios.get('/posts', {
params: {
title: oldTitle
}
})
//or if its a vuex state item...
//let post = this.$store.state.posts.find((p) => p.title === oldTitle)
return post
},
}