Vuex store type with Typescript

前端 未结 3 1740
暗喜
暗喜 2021-01-11 09:41

I\'m trying to get a Vuex store to be Typescript friendly. I\'m building the store as explained here. However, when I access this.$store from a component, the t

3条回答
  •  北海茫月
    2021-01-11 09:57

    You could declare a property in your component so typescript will apply typing. I use this for $refs all the time but it works for the $store too. You don't need to do anything with the property apart from marking it with ! operator to tell the transpiler that vue will set the variable for you.

    $store!: Store;
    

    Another alternative I use is to use the MapState or MapGetters component helpers. They create the properties for you so you can use them in the template. Example:

    @Component({
      computed: mapState({
        userFullName: (state: any) => state.user.fullName,
        userEmail: (state: any) => state.user.email
      })
    })
    

    Don't forget to import the Store, your vuex state class and any helper you use import { Store, mapState } from "vuex";.

提交回复
热议问题