The scenario is relatively straight-forward: we have a Vuex module located in
~/store/projects.js
and we'd like to define a getter called currentProject
which .find()
s a project based on the current route params.
We'll start by installing the
vuex-router-sync
module:
> yarn add vuex-router-sync
We then define a Nuxt.js Plugin to sync()
the store and the router:
// ~/plugins/vuex-router-sync.js
import { sync } from 'vuex-router-sync';
export default ({ app: { store, router } }) => {
sync(store, router);
};
(Sourced from this GitHub issue.)
For this to be run during initialisation we need to declare it in our Nuxt.js config:
// nuxt.config.js
module.exports = {
plugins: ['~/plugins/vuex-router-sync'],
};
The module 'route' is now available in the store and is kept in sync with the
vue-router
instance.
Returning to our 'projects' Vuex module, we are now able to define a getter that
.find()
s a project based on the current route parameter id
:
// ~/store/projects.js
export const state = () => ({ projects: [] });
export const getters = {
currentProject: (state, getters, rootState) =>
state.projects.find(project => project.id === rootState.route.params.id),
};