using mapState in vue + typescript

Viewed 137

I'm writing an application in vue+vuex+typescript after years of being away from vue. I get the concepts, but a lot has changed!

I'm running into a weird issue when trying to use the vuex mapState helper function. I have a store module called animationCanvas:

import { Module } from 'vuex'
import { RootState } from '../types'
import { AnimationCanvasState } from './types'

const state: AnimationCanvasState = {
  frames: [],
}

export const animationCanvas: Module<AnimationCanvasState, RootState> = {
  state,
}

And I'm pulling it into my root store module and registering it:

import { createStore, StoreOptions } from 'vuex'
import { RootState } from './types'
import { animationCanvas } from '@/store/modules/AnimationCanvas'

const store: StoreOptions<RootState> = {
  modules: {
    animationCanvas,
  },
}

When I use the store in the component pulling directly from the $store property it works fine:

import { Vue, Options } from 'vue-class-component';

@Options({
    name: 'Animation Canvas',
    computed: {
        frames() {
            return this.$store.state.animationCanvas.frames;
        },
    },
})
export default class AnimationCanvas extends Vue {
...

works

But when I try to add it via the mapState helper function I get nothing:

import { Vue, Options } from 'vue-class-component';
import { mapState } from 'vuex';

@Options({
    name: 'Animation Canvas',
    computed: {
        ...mapState('animationCanvas', ['frames']),
    },
})
export default class AnimationCanvas extends Vue {

mapState not working

And I know that module is there and named correctly, partially because it worked in the $store style path, but also because I can see it in the dev tools:

store in dev tools

I've been looking around in the docs but I can't quite figure it out. Any ideas?

1 Answers

Nowhere in your code I see that you have namespaced your Vuex module. I don't know the syntax for typescript but in plain JS you would do

const store = {
  modules: {
    animationCanvas: {
       namespaced: true,
       state: ...
    }
  }
}

You can check this by doing console.log(this.$store) in your component and seeing the structure of the object. In your getters you should have something like:

getters: {
   'animationCanvas/frames': ...
}
Related