How to use mapState function in typescript syntax when using vuex?

前端 未结 2 931
温柔的废话
温柔的废话 2021-02-19 05:59

I\'m using typescript syntax in my vuejs project that integrated with vuex. I want to use mapState method as computed in my .ts file but I got a syntax error. Currently I am usi

相关标签:
2条回答
  • 2021-02-19 06:10

    You may call mapState within the Component annotation:

    import { Component, Vue } from 'vue-property-decorator';
    import { mapState } from 'vuex';
    
    @Component({
      // omit the namespace argument ('myModule') if you are not using namespaced modules
      computed: mapState('myModule', [ 
        'count',
      ]),
    })
    export default class MyComponent extends Vue {
      public count!: number; // is assigned via mapState
    }
    

    You may also use mapState to create new computeds based off of your state:

    import { Component, Vue } from 'vue-property-decorator';
    import { mapState } from 'vuex';
    import { IMyModuleState } from '@/store/state';
    
    @Component({
      computed: mapState('myModule', {
        // assuming IMyModuleState.items
        countWhereActive: (state: IMyModuleState) => state.items.filter(i => i.active).length,
      }),
    })
    export default class MyComponent extends Vue {
      public countWhereActive!: number; // is assigned via mapState
    }
    
    0 讨论(0)
  • 2021-02-19 06:33

    Easier using JS Spread syntax:

    <template>
      <div class="hello">
        <h2>{{ custom }}</h2>
        </div>
    </template>
    
    <script lang="ts">
    import { Component, Prop, Vue } from 'vue-property-decorator';
    import { mapState } from 'vuex';
    
    @Component({
      computed: {
        ...mapState({
          title: 'stuff'
        }),
        // other stuff
      },
    })
    export default class HelloWorld extends Vue {
    
      title!: string;
    
      public get custom():string {
        return this.title;
      }
    }
    </script>
    

    Your store:

    import Vue from 'vue';
    import Vuex from 'vuex';
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
      state: {
        stuff: 'some title',
      },
      mutations: {
    
      },
      actions: {
    
      },
    });
    
    0 讨论(0)
提交回复
热议问题