在TypeScript + Vue的项目中, Vuex的mutations写法报错

熠辉
  • 2.5k

项目使用vue-cliwebpack模板初始化, 引入vuex并同时安装了vue-class-component. 在mutations.ts文件中, 如果使用以下的第一种方法定义mutation写法会报错(typescript没有任何编译错误), 但是第二种方法不会报错:

import * as types from './mutations-types'

export default {
  //方法1:会报错
  [types.INCREMENT_NUMBER](state, data: number):void {
    state.initNumber = data;
  }

  //方法2: 不会报错
  // incrementNumber(state, data:number):void {
  //   state.initNumber = data;
  // }
}

报错信息如下:

clipboard.png

  • store/index.ts文件如下:

    import Vue from 'vue'
    import Vuex from 'vuex'
    import state from './state'
    import mutations from './mutations'
    import actions from './actions'
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
      state,
      mutations,
      actions
    })
  • main.ts文件如下:

    // The Vue build version to load with the `import` command
    // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
    import Vue from 'vue'
    import App from './App.vue'
    import router from './router'
    import store from './store'
    
    Vue.config.productionTip = false
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      store,
      template: '<App/>',
      components: { App }
    })
    
  • vue-shim.d.ts文件如下:

    declare module "*.vue" {
      import Vue from "vue";
      export default Vue;
    }
  • tsconfig.json文件如下:

    {
      "include": [
        "src/**/*"
      ],
      "exclude": [
        "node_modules"
      ],
      "compilerOptions": {
        "allowSyntheticDefaultImports": true,
        "experimentalDecorators": true, 
        "allowJs": true,
        "module": "esnext",
        "target": "es5",
        "moduleResolution": "node",
        "isolatedModules": true,
        "strictFunctionTypes": false,
        "lib": [
          "dom",
          "es5",
          "es6",
          "es7",
          "es2015.promise"
        ],
        "sourceMap": true,
        "pretty": true
      }
    }
回复
阅读 3.8k
2 个回答
✓ 已被采纳
import * as types from './mutations-types'

const mutations: any = {
  [types.INCREMENT_NUMBER](state, data:number): void{
    state.initNumber += data;
  }
}

export default mutations

已经解决该问题, 使用vuex提供的MutationsTree方法即可解决个报错问题, mutations.ts中的代码如下

//mutations.ts

import * as types from './mutations-types'
import { MutationTree } from 'vuex'

const mutations: MutationTree<any> = {
  [types.INCREMENT_NUMBER](state, data:number): void {
    state.initNumber += data;
  }
}

export default mutations
宣传栏