programing

Typecript Vuex 객체가 알 수 없는 유형인 Vue Vuex

prostudy 2022. 3. 10. 22:38
반응형

Typecript Vuex 객체가 알 수 없는 유형인 Vue Vuex

나는 타입스크립트의 Vuex를 작동시키려 하는데 문제가 있다.나는 아래 첫 번째 그림과 같이 딱 맞는 타이프 없이 예시를 했다.나는 Vuex 모듈을 생성한 후 아래와 같이 추가한다.

src -> store -> index.js

import Vue from 'vue';
import Vuex from 'vuex';
import robotsModule from './modules/products';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    products: productsModule
  },
});

src -> store -> modules -> product.js

import axios from 'axios';

export default {
  namespaced: true,
  state: {
    products: [],
  },
  mutations: {
    addProduct(state, product) {
      state.products.push(product);
    },
    updateProduct(state, products) {
      state.parts = products;
    },
  },
  actions: {
    getProducts({ commit }) {
      axios
        .get('/api/products')
        .then(result => commit('updateProduct', result.data))
        .catch(console.error);
    }
  },
};

이제 내가 타이프릭을 사용하고 싶을 때, 그것은 계속 불평한다.

"binding 요소 'commit'은 암시적으로 'any' 타입을 가지고 있다.

보다시피 나는 현재 그 상태를 잘못된 것으로 보이는 으로 지정했다.어떻게 하면 이 문구를 타이프로 잘 만들 수 있을까?

src -> store -> modules -> product.ts

import axios from 'axios';
import { Product } from '@/models/product';

export default {
  namespaced: true,
  state: {
    products: new Array<Product>(),
  },
  mutations: {
    updateProducts(state: any, products: Product[]) {
      state.products = products;
    },
    addProduct(state: any, product: Product) {
      state.products.push(product);
    },
  },
  actions: {
    getProducts({ commit }) {
      axios
        .get('/api/products')
        .then(result => commit('updateProducts', result.data))
        .catch(console.error);
    },
  },
};

나는 온라인에서 내가 함수로써 커밋을 가질 필요가 있다는 것을 보여주는 예를 발견했다.

getProducts({ commit }: { commit: Function }) {

여기의 전체 파일

import axios from 'axios';

import { Product } from '@/models/product';
import State from '@/models/state';

export default {
  namespaced: true,
  state: {
    items: new Array<Product>(),
  } as State,
  mutations: {
    updateProducts(state: State, products: Product[]) {
      state.items = products;
    },
    addProduct(state: State, product: Product) {
      state.items.push(product);
    },
  },
  actions: {
    getProducts({ commit }: { commit: Function }) {
      axios
        .get('/api/products')
        .then(result => {
          commit('updateProducts', result.data);
        })
        .catch(console.error);
    },
  },
};

또한 State 클래스를 만들면 내 상태 대상이라고 말할 수 있다.

import Vue from 'vue';
import { Product } from '@/models/product';

export default class State extends Vue {
  items: Product[] = new Array<Product>();
}

업데이트 15-03-118 - 내 직장 동료가 이제 https://www.npmjs.com/package/direct-vuex을 사용했다고 말했는데, 이것은 더 쉬워진답니다!

Andrew의 대답에 기초하여 몇 가지 인터페이스를 도입하여 코드를 약간 정리할 수 있다.

export interface CommitFunction {
    commit: Commit;
}

export interface CommitStateFunction<T> extends CommitFunction {
    state: T;
}

그래서 당신의 행동은 다음과 같이 보일 것이다.

actions: {
    getProducts({ commit }: CommitFunction) { /* logic here */ },
    updateProducts({ commit, state }: CommitStateFunction<State>) { /* logic here */ }
}

참조URL: https://stackoverflow.com/questions/62937216/vue-vuex-with-typescript-vuex-object-not-known-type

반응형