Vuex状态和vue路由器

问题描述 投票:1回答:3

我正在尝试与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>

当我单击一个网格文章时,我希望它重定向到带有相同id文章数据的articlePage.vue组件。

到目前为止,在我的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,并访问正确的数据。但它不起作用。我究竟做错了什么?

谢谢你的帮助! :)

javascript arrays vue.js vuex vue-router
3个回答
1
投票

Name your routes并传递你的文章像这样:

<router-link :to="{ name: 'article', params: { id: article.id }}">{{article.title}}</router-link>

另外,使用Array.prototype.find可能比使用Array.prototype.filter更好,因为第二个会在你的情况下给你一个单元素数组。


1
投票

您应该使用find而不是filter,并在find回调函数中添加return

selectedArticle() {

  let article = this.$store.state.articles.find(article => {

    return article.id == this.$route.params.id

  });

  return article;

}

1
投票

首先,定义您的路线并了解如何创建动态路线:

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发送的参数,记得在组件道具中定义他:

export default {
  name: "articlePage",
  props: ["category"],
...}
© www.soinside.com 2019 - 2024. All rights reserved.