How to use vuex map helpers in composition api in Nuxt

Viewed 1222

I spent a lot of time figuring out how to use vuex map helper function and finally, I didn't figure it out.

Now I have something like this:

setup (_, { root: { $store } }) {
    onMounted(() => {
      $store.commit('app/setApplicationWidth', innerWidth)
      console.log($store.getters['app/getApplicationWidth'])
    })
  }

So how I can use mapGetters, and mapMutations in composition API?

My vuex store looks like this: /store/app.ts

import { GetterTree, MutationTree, ActionTree } from 'vuex'

export const state = () => ({
  appWidth: <Number> 0
})

export type RootState = ReturnType<typeof state>

export const mutations: MutationTree<RootState> = {
  setApplicationWidth (state: any, payload: Number) {
    state.appWidth = payload
  }
}

export const getters: GetterTree<RootState, RootState> = {
  getApplicationWidth (state: any): Number {
    return state.appWidth
  }
}

export const actions: ActionTree<RootState, RootState> = {}

1 Answers

One option is vuex-composition-helpers here. It seems to work from my cursory examination. However, there are some hiccups that you might want to pay attention to so you get off on the right foot:

  1. You need to transpile it by adding to nuxt.config.js:
  build: {
...
    transpile: ['vuex-composition-helpers']
  }

Otherwise you'll get an inscrutable "unknown keyword export" error.

  1. Nested stores use the alternate *Namespaced* methods:
import { useNamespacedGetters } from 'vuex-composition-helpers'

export default defineComponent({
...
  setup(_props, context) {
    const { articles, articlesInfo } = useNamespacedGetters('articles', [
      'articles',
      'articlesInfo',
    ])

All in all it's just a little better than the "raw" method of using computed on the store directly:

import { computed } from '@nuxtjs/composition-api'
...
    const articles2 = computed(
      () => context.root.$store.getters['articles/articles']
    )
Related