javascript - Vuex 状态和 vue-router
问题描述
我正在尝试用 vuejs 做一个博客,但我有点卡住了。我所有的文章数据都在这样的 Vuex 商店中:
export const store = new Vuex.Store({
state: {
articles: [{
title: "Article 1",
id: 1,
content:"Article 1 content"
}, {
title: "Article 2",
id: 2,
content:"Article 2 content"
}
}]
}
我的主页上有一个文章网格:
<div class="item-article" v-for="article in articles">
<router-link :to="{path: '/article/'+article.id}"></router-link>
<div>{{ article.title }}</div>
</div>
当我点击一个网格文章时,我希望它重定向到 articlePage.vue 组件,其中包含相同 id 文章的数据。
到目前为止,在我的 articlePage.vue 组件上,我使用了这个:
<div v-for="article in selectedArticle">
<h1>{{ article.title }}</h1>
<p>{{ article.content }}</p>
</div>
computed: {
selectedArticle(){
return this.$store.state.articles.filter(article => article.id == this.$route.params.id);
}
}
我想用$route.params.id
它来捕获 VueX 中的匹配 id,并访问正确的数据。但它不起作用。我究竟做错了什么?
谢谢你的帮助!:)
解决方案
首先,定义您的路线并查看如何创建动态路线:
const routes = [
{
path: '/articles/:id',
name: 'articles',
component: articlePage,
props: true
}
]
在您的 Vue 实例中,传递路线和vuex 商店:
new Vue({
store,
router: routes,
el: '#app',
render: h => h(App)
})
在 Vuex 商店的 getters 属性中,您需要创建一个按 id 过滤/查找文章的方法,如下所示:
getArticlesById: (state) => (id) => state.articles.find(article => article.id === id)
最后,在您的 mounted() 方法中,调用他:
this.article = this.$store.getters.getArticlesById(this.articleId)
this.articleId是通过 URL 发送的参数,记得在组件 props 中定义他:
export default {
name: "articlePage",
props: ["category"],
...}
推荐阅读
- android - 元数据中android:value的使用——Android
- c++ - 如何使用al_draw_bitmap_region?
- python - 使用 python 在 XML 文件中获取唯一的项目对
- php - PHP PDO 在执行带参数的准备好的语句时返回 false
- javascript - 使用 async/await 仍然返回 undefined
- python - Python concurrent.futures.ThreadPoolExecutor max_workers
- c++ - *min-heap* 的良好 C++ 数据结构实现,增加 *hash table*
- vhdl - 在 VHDL 中为模块创建“初始化”和“结束”信号
- ruby - 如何正确使用 Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest 对象?
- javascript - 我需要有关如何从节点 js 在 sql server 中插入的帮助