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

Saul Hardman @saul

About: Front-end web developer interested in performance, design systems, and static site generators.

Location:
Copenhagen, Denmark
Joined:
Nov 7, 2017

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

Publish Date: Jul 24 '19
7 0

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

Comments 0 total

    Add comment