美文网首页
使用TypeScript+Vuex

使用TypeScript+Vuex

作者: nomooo | 来源:发表于2020-02-18 15:38 被阅读0次

    安装

    npm install --save @vuets/vuex
    

    直接上代码
    store.ts/vuex.ts部分

    import Vue from 'vue';
    import Vuex from 'vuex';
    
    Vue.use(Vuex);
    // 定义类型
    interface RootState {
      name: string;
    }
    export default new Vuex.Store({
      state: {
        // 初始值
        name: 'Mr Wang',
      },
      getters: {
        // 获取name方法
        getName: (state: RootState) => state.name,
      },
      mutations: {
        // 修改name方法
        changeName: (state: RootState, params: string) => {
          state.name = params;
        },
      },
    
    });
    

    使用部分

    import { Getter } from '@vuets/vuex';
      // 获取name值
      @Getter('getName') public name!: string;
      public mounted() {
        console.log('第一次获取');
        console.log(this.name);
        setTimeout(() => {
          // 修改name值
          this.$store.commit('changeName', 'Mr Yang');
          console.log('第二次获取');
          console.log(this.name);
        }, 3000);
      }
    
    
    打印截图

    end

    相关文章

      网友评论

          本文标题:使用TypeScript+Vuex

          本文链接:https://www.haomeiwen.com/subject/upbgfhtx.html