[Vuejs]-Nuxtjs Page components are not updated even if the vuex store is updated

0👍

Since vex store are reactive you can retrieve a store’s state by returning it within a computed prooperty. See getting vuex state into components

what you are doing is:

<tag-contents v-for="article in $store.state.article_list" :key="article.id"></tag-contents>

instead do this:

<template>
  ...
    <tag-contents v-for="article in articles" :key="article.id"></tag-contents>
  ...
</template>

<script>
export default  {
    ...
    fetch ({store, params}) {
        api.get_articles()
            .then((data) => {
                store.dispatch('mutateArticleList', data)
            })
    },
    created () {
        console.log('index created length', this.$store.state.article_list.length)
    },
    computed:{
        articles(){
            return this.$store.state.article_list;
        }
    }
}
</script>

whenever store’s state is updated the computed prperty articles is reevaluated and cuases the DOM to update

One more things to mention:

Since actions are for asynchronous tasks you can move your RESTapi fetch logic into you mutateArticleList action and commit a mutation to update state by passing the data recieved from ajax call as payload to the mutation.

So now your code should be:

store

const createStore = () => {
  return new Vuex.Store({
    state: {
      article_list: []
    },
    mutations: {
      updateArticleList (state, payload) {
        state.article_list = payload
        console.log('article list length', state.article_list.length)
      }
    },
    actions: {
      mutateArticleList ({commit}, payload) {
          api.get_articles()
            .then((data) => {
                commit('updateArticleList', data);
            })
      }
    }
  })
}

index.vue

<template>
  ...
    <tag-contents v-for="article in articles" :key="article.id"></tag-contents>
  ...
</template>

<script>
export default  {
    ...
    fetch () {
        this.$store.dispatch('mutateArticleList', data)
    },

    computed:{
        articles(){
            return this.$store.state.article_list;
        }
    }
}
</script>

Leave a comment