Bind data to component with Vuex

Viewed 243

I'm new to vue.js and I'm trying to use vuex. Here is my issue:

I have a list of articles (which is a component) linked with a store with v-for="article in articles and a computed property:

computed: {
        articles() {
            return this.$store.state.articles
        }
    }

So here is the data in my store:

 state: {
    articles: [{
        title: "Article 1",
        id: 1,
        description: "Article 1",
      }, {
        title: "Article 2",
        id: 2,
        description: "Article 2",
      }
     }]
}

When I click on an article, I want it to redirect to the article page template (which is a component) with <router-link :to="{path: '/article/'+article.id}"></router-link>.

What I'm trying to do is bind the data of the correct article in the articlePage template.

The issue is that if I apply the same computed property to my articlePage.vue component with a v-for, I will display all of the article on the same page. I would like to display only the matching id component.

How can I do that?

Thank you for your time :)

1 Answers

From your comments I understand that you use vue-router module So in your routes.js (or structure ) your must have something like this

const router = new VueRouter({
   routes: [
    { path: '/articles', component: articlesPage },
    { path: '/article/:id', component: articlePage }
  ]
})    

Then in your articlePage component you can extract ":id" like this:

this.$route.params.id

because vue-router gives you access to the object $route with methods and properties Check more here https://router.vuejs.org/guide/essentials/dynamic-matching.html

then you can use it to search the articles array and find the data and present them e.x.

computed:{
   selectedArticle(){
     var article_id = this.$route.params.id;
     var articles = this.$store.state.articles;
     var article = null;
     for(var a=0;a<articles.length;a++){
         if(articles[a].id == article_id ){
           article = articles[a];
           break;
         }
     } 
     return article;
   }
}    
Related