DEV Community

Saul Hardman
Saul Hardman

Posted on • Originally published at viewsource.io on

Using `vuex-router-sync` with Vuex Modules and Nuxt

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
Enter fullscreen mode Exit fullscreen mode

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);
};
Enter fullscreen mode Exit fullscreen mode

(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"]
};
Enter fullscreen mode Exit fullscreen mode

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)
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)