Created
November 30, 2021 15:41
-
-
Save Tardigrada777/31760b42bec5ad35f6396204d56fd3eb to your computer and use it in GitHub Desktop.
Reusable paginated Vuex module.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const Mutations = { | |
APPEND_ITEMS: 'APPEND_ITEMS', | |
CLEAR_LIST: 'CLEAR_LIST', | |
SET_PAGINATION_SETTINGS: 'SET_PAGINATION_SETTINGS', | |
SET_OFFSET: 'SET_OFFSET' | |
}; | |
const Default = { | |
Offset: 0, | |
ItemsPerPage: 4, | |
}; | |
export const paginatedModule = ({ | |
namespaced = true, | |
load, | |
}) => { | |
return { | |
namespaced, | |
state: { | |
items: [], | |
settings: { | |
offset: Default.Offset, | |
limit: Default.ItemsPerPage, | |
itemsPerPage: Default.ItemsPerPage, | |
}, | |
status: { | |
page: 0, | |
} | |
}, | |
mutations: { | |
[Mutations.APPEND_ITEMS](state, items) { | |
state.items = state.items.concat(items); | |
}, | |
[Mutations.CLEAR_LIST](state) { | |
state.items = []; | |
}, | |
[Mutations.SET_PAGINATION_SETTINGS](state, settings) { | |
state.settings = { | |
...state.settings, | |
...settings, | |
}; | |
}, | |
[Mutations.SET_OFFSET](state, offset) { | |
state.settings.offset = offset; | |
}, | |
}, | |
actions: { | |
async fetchMore({ state, commit }) { | |
const { offset, limit } = state.settings; | |
const items = await load({ offset, limit }); | |
commit(Mutations.APPEND_ITEMS, items); | |
commit(Mutations.SET_OFFSET, offset + state.settings.itemsPerPage); | |
}, | |
}, | |
getters: { | |
paginationStatus(state) { | |
return { | |
pageNumber: state.items.length / state.settings.itemsPerPage, | |
loaded: state.items.length, | |
}; | |
}, | |
}, | |
}; | |
}; | |
// connect to vuex | |
const store = { | |
// state, mutations, etc. | |
modules: { | |
posts: paginatedModule({ | |
load: async ({ offset, limit }) => { | |
return await axios.get(`/posts?offset=${offset}&limit=${limit}`); | |
}, | |
}), | |
} | |
}; | |
// component | |
import { mapState, mapGetters } from 'vuex'; | |
export default { | |
computed: { | |
...mapState('posts', { | |
items: 'posts', // reactive posts list | |
}), | |
...mapGetters('posts', ['paginationStatus']) // reactive pagination status | |
}, | |
methods: { | |
...mapActions('posts', ['fetchMore']), // method to load more posts (items) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment