LDUBBS
LDUBBS

Reputation: 603

Pagination in Vuex Store

I have cloned this awesome shopping cart repo from https://github.com/vueschool/learn-vuex, and i get data like this:

ProductList.vue

<template>
    <div>
<ul>
        <li v-for="product in products">
           - {{product.name}} - {{product.price}}
        </li>
      </ul>
</div>
</template>

<script>
methods: {
      ...mapActions({
        fetchProducts: 'products/fetchProducts'
      })
    }
</script>

export default new Vuex.Store({
    state: {
        products: {},
    },
    actions: {
    fetchProducts({commit},data) {
            axios.get(`api/product`).then((response) => {
            commit('updateProducts', response.data);
        })
    },
    mutations: {
        updateProducts (state, products) {
            state.products = products
        }
    }
});

I'm trying to paginate results and need help in that direction, do i need to create a pagination state or new module in the vuex store, thanks in advance.

Upvotes: 4

Views: 6026

Answers (2)

Mike Ross
Mike Ross

Reputation: 2972

Try following

I use one of the RenderlessLaravelVuePagination component for pagination.

<pagination :data="products" @pagination-change-page="getProducts"></pagination>

and remaining code is below

export default {
  name: 'ProductList',
  mounted() {
    this.getProducts();
  },
  methods: {
    getProducts(page = 1){
      this.$store.dispatch('getProducts',{
        page: page
    });
  },
}

Hope this works for you.

Upvotes: 2

spiCkyyy
spiCkyyy

Reputation: 11

You need to define meta object in order to store the meta data returning from your axio post. Then, you can use that meta object in your vue.

Do something like this:

export default new Vuex.Store({
    state: {
        products: {},
        productsMeta: {}

    },
    actions: {
        getProducts({commit},data) {
            axios.get(`api/product`).then(response => {
            this.productsMeta = response.meta;
            }).commit('updateProducts', response.data);
        })
    },
    mutations: {
        updateProducts (state, products) {
            state.products = products
        }
    }
});

Upvotes: 0

Related Questions