简体   繁体   中英

How to re-render component after update data in store

I have a problem with re-render my table component when data in my store is updated, I have a simply table with v-for like below:

<tr v-for="d in getDatas" v-bind:key="d.id">

and buttons to change page:

<button class="fa fa-chevron-left" @click="previousPage"/>
<button class="fa fa-chevron-right" @click="nextPage"/>

I load data to my datas before i open my component where is this table, and i get this data from store like below:

  computed: {
    getDatas () {
      return this.$store.getters.getDatas;
    }
  },

but how to update my store with data when i click on button nextPage or previousPage ? here is my methods:

  methods: {
      ...mapActions(["fetchDatas"]), //this is my action
      nextPage() {
        this.currentPage += 1;
      },
      previousPage() {
        if(this.currentPage != 1) {
          this.currentPage -= 1;
        }
      },

and my action:

    async fetchDatas({ commit },{ currentPage}) {
        const data = await fetch(`someURL&perPage=${currentPage}`);
        const response = await data.json();
        commit('setData', response);
    }

so, how to reload component and my store when i click on my next/previousPage ?

You already have a computed property that automatically updates when your store updates. All you have to do is trigger the action in your methods for changing pages.

nextPage() {
   this.currentPage += 1;
   this.fetchDatas(this.currentPage);
},
previousPage() {
   if(this.currentPage != 1) {
      this.currentPage -= 1;
      this.fetchDatas(this.currentPage);
   }
},

And unless you have a compelling reason for requiring an Object parameter to the action, I would remove the curly braces entirely:

async fetchDatas({ commit }, currentPage) {
...

Otherwise you need to call it with this.fetchData({currentPage: this.currentPage}) .

You can setup a watch on the currentPagevariable where the getDatas action would be fired again on the change of the current page after clicking the buttons.

A watch can be declared as so:

watch: {
        currentPage: function (newValue) {
            this.$store.dispatch('fetchDatas', this.currentPage)
        },
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM