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

Hiya, I'm Saul Hardman, a front-end web developer based in Copenhagen, Denmark. I'm currently available for work, so if you need help building websites, web applications, and everything in between get in touch!

To stay up to date, follow me on Twitter and GitHub and be sure to subscribe to the RSS feed.