Right-Click → View Page Source

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

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),

Join the converstation on the DEV Community or send a Webmention

About the author

A profile photo of Saul Hardman

Saul Hardman is a contract front-end web developer based in Copenhagen, Denmark. During his career he's worked with the likes of The Guardian, UNIT9, and AllofUs. As of now he's helping Realla with front-end architecture, performance, and technical SEO.

To stay up to date, follow Saul on Twitter and GitHub or subscribe to the RSS feed.