IT이야기

VS 코드의 Vuex 스토어에 대한 인텔리센스

cyworld 2022. 5. 7. 09:38
반응형

VS 코드의 Vuex 스토어에 대한 인텔리센스

나는 , , 그리고 비주얼 코드의 을 이용하여 애플리케이션을 만들고 있다.는 내선 확장 장치를 설치했다.나는 대부분의 프로젝트를 위해 나에게 무감각을 주기 위해 정의 파일을 만들었지만, 나는 무감각에 내 상점을 추가하는 방법을 알아낼 수 없었다.정의 설명서를 읽어 보았지만, 어떻게 해야 할지 잘 모르겠어.내 목표는 안에 있는 모든 것에 대해 무감각해질 수 있는 것이다.this.$store.현재, 는 에 대해 무감각을 제공한다.state,getters, 등. 그러나 그것은 다음 레벨에 대한 무감각을 제공하지 않는다(예.this.$store.state.TestVariable어떻게 하면 내 상점에 대한 감각을 얻을 수 있을까?

계약 관리 스토어

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        Contract: new Library.Model.Entity.Contract()
    }
});

계약 구성요소

<template>
    <contract-line></contract-line>
</template>

<script lang="ts">
    import Vue from 'vue';
    import Vuex from 'vuex';
    import store from '../store/ContractManagementStore';
    import ContractLine from "./ContractLine.vue";

    export default Vue.extend({
        name: 'contract-management',
        store,
        components: {
            'contract-line': ContractLine
        }
    });
</script>

<style>

</style>

계약 라인 구성 요소

<template>
    <button v-if="CanDelete"></button>
</template>

<script lang="ts">
    import Vue from 'vue';
    import Vuex from 'vuex';

    Vue.use(Vuex);

    export default Vue.extend({
        computed:{
            CanDelete(): Boolean {
                // Looking for intellisense after this.$store.state.
                return this.$store.state.Contract.ContractStatus.Value === Library.Enums.ContractStatus.Draft
            }
        }
    });
</script>

<style>

</style>

자신의 상태를 명시적으로 입력하면 이를 달성할 수 있다.

Contract Management Store.ts

export interface ContractManagementState {
    Contract: ContractType;
}

구성 요소:

...
(this.$store as Store<ContractManagementState>).<intellisense here>

불행히도 이런 식으로 주(州)에 접근할 때마다 이렇게 해야 한다.이는 Vuex가 모듈의 존재를 선언하기 위해 모듈 증강을 사용하는 방식 때문이다.$store유형별 특성

vuex/types/vue.d.ts:

declare module "vue/types/vue" {
  interface Vue {
    $store: Store<any>;
  }
}

당신은 당신의 콘크리트 상태 타이핑으로 그것을 무시할 수 없다. (결국 이것을 모듈 확대라고 부른다).가능한 해결책은 상점 접속을 위해 게이터를 사용하는 것이다.vuex-typecriptvuex-typex와 같은 getter, mutator 및 작업에 형식 정보를 추가하기 위한 몇 가지 형식 라이브러리가 존재한다.

나 역시 이 이틀에 걸쳐 이 문제를 접하게 되고, 이 문제의 타이핑 인식의 부족을 견딜 수가 없다.this.$store.state.

@georg-grab의 해결책은 나에게 이런 영감을 준다.

  1. 난 TypeScript에 익숙하지 않아...그래서 이 해결책은 어리석지만 효과가 있다.
  2. 내 해결책은 오직 상대만 할 수 있다.this.$store.state, 같은 다른 모든 것this.$store.dispatch아직도 인텔리센스가 없다.
// store/index.ts
// I will not explain vuex modules here. Please see the doc of Vuex by yourself.
import Vue from 'vue'
import Vuex, {Store} from 'vuex'

import auth, {State as AuthState} from './modules/auth'  // State is an interface defined in module.

export interface State {
  auth: AuthState
}

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    auth
  }
}) as Store<State>  // Force TypeScript compiler to recognize this as Store<State> instead of Store<any>.

그런 다음 Vue 플러그인을 통해 글로벌 인스턴스 Getter를 추가하십시오.

// main.ts
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store, { State } from './store'

declare module 'vue/types/vue' {  // Tell TypeScript the type of this.$state is our defined 'State'
  interface Vue {
    $state: State
  }
}
const TypedState = {  // define a Vue plugin. See https://vuejs.org/v2/guide/plugins.html
  install(Vue: any) {  // For simplify, didn't pass 'State' via options
    Object.defineProperty(Vue.prototype, '$state', {  // Add a global getter 'this.$state' in vm
      get (): State { return store.state as State }  // Force TypeScript compiler to recognize this as our defined 'State'
    })
  }
}
Vue.use(TypedState)

이제 다음 값에 액세스할 수 있음this.$store.state경유로this.$state, IntelliSense와 함께.

또한 인터페이스의 "덮어쓰기"를 원한다.vm.$store(출처)Store<any>Store<State>)) 그러나 TypeScript는 그런 일을 할 방법이 없는 것 같다.

declare module 'vue/types/vue' {
  interface Vue {
    $store: Store<State>   // Error
  }
}

참조URL: https://stackoverflow.com/questions/50644005/intellisense-for-vuex-store-in-vs-code

반응형