itsource

Vuex-module-decorator, 액션 내 상태 변경

mycopycode 2022. 11. 15. 21:41
반응형

Vuex-module-decorator, 액션 내 상태 변경

vuex-module-decorator를 사용하면authenticate상태를 변환하는 액션입니다.

@Action
public authenticate(email: string, password: string): Promise<Principal> {
    this.principal = null;
    return authenticator
      .authenticate(email, password)
      .then(auth => {
          const principal = new Principal(auth.username);
          this.context.commit('setPrincipal', principal);
          return principal;
      })
      .catch(error => {
          this.context.commit('setError', error);
          return error;
      });
}

// mutations for error and principal

그러나 다음 메시지와 함께 실패합니다.

처리되지 않은 약속 거부 오류: "ERR_ACTION_ACCESS_UNDEFINED:접속을 시도하고 있습니까?someMutation() 또는 this.어떤 @Action 내에서의 Getter?이 기능은 다이내믹모듈에서만 동작합니다.다이내믹하지 않은 경우 this.context.commit("mutationName", payload) 및 this.context.getters["getterName"]를 사용합니다.

이해가 안 되는 것은 이 기능이@MutationAction그리고.async하지만 반품 타입이 그리워요.Promise<Principal>.

@MutationAction
public async authenticate(email: string, password: string) {
    this.principal = null;
    try {
        const auth = await authenticator.authenticate(email, password);
        return { principal: new Principal(auth.username), error: null };
    } catch (ex) {
        const error = ex as Error;
        return { principal: null, error };
    }
}

--

현시점에서는 막혔다고 생각되며, 이 기능을 구현하기 위해 도움을 받고 싶습니다.@Action상태를 변환하고 특정 유형을 반환할 수 있습니다.Promise.

주석에 rawError 옵션을 추가하면 다음과 같이 됩니다.

   @Action({rawError: true})

그리고 정상적으로 에러가 표시됩니다.이는 라이브러리 "vuex-module-decorators" 랩 오류가 발생했기 때문입니다.이것에 의해, 조작할 수 있는 RawError 를 취득할 수 있습니다.

이 답변은 특정 질문에 대한 답변이 아니기 때문에 부결시킬 수 있습니다.대신 타이프스크립트를 사용하고 있다면 vuex를 사용하지 말 것을 제안합니다.지난 한 달 동안 vue /vuex와 타이프스크립트를 배우려고 노력했습니다.나는 타자본을 사용하는 것의 이점을 굳게 믿고 있기 때문에 타자본을 사용하는 것에 전념하고 있다.다시는 raw javascript를 사용하지 않겠습니다.

누군가 처음부터 vuex를 사용하지 말라고 했더라면 지난 4주 중 3주 정도는 목숨을 건졌을 거예요.그래서 저는 그 통찰력을 다른 사람들과 공유하기 위해 여기에 있습니다.

핵심은 Vue 3의 새로운 참조 구현입니다.이것이 vuex와 타이프스크립트의 판도를 변화시키는 것입니다.이를 통해 vuex에 의존하지 않아도 자동으로 상태를 리액티브하게 랩할 수 있습니다.대신 vue 3의 ref 구성을 사용하여 직접 수행할 수 있습니다.다음은 ref를 사용하는 앱과 이전에 vuex를 사용하려고 했던 타이프스크립트 클래스의 작은 예입니다.

주의 1: 이 접근방식을 사용할 때 손실되는 것은 vuex 개발 도구입니다.메모2: Knockout.js에서 Vue로 25,000줄(7,000개의 유닛 테스트 포함)의 타이프스크립트를 이식하고 있기 때문에 편견이 있을 수 있습니다.Knocko.js는 Observatibles(Vue의 ref)와 바인딩 제공에 관한 모든 것이었다.돌이켜보면, 시대를 앞서고 있었지만, 다음과 같은 지지와 지지를 얻지 못했습니다.

예, vuex를 사용하지 않는 vuex 모듈 클래스를 만듭니다.이것을 appStore.ts에 넣습니다.간단하게 하기 위해서, 유저 정보와 유저가 로그인 하고 있는 클럽의 ID가 포함됩니다.사용자는 클럽을 전환할 수 있으므로 이를 위한 액션이 있습니다.

export class AppClass {
  public loaded: Ref<boolean>;
  public userId: Ref<number>;
  public userFirstName: Ref<string>;
  public userLastName: Ref<string>;
  // Getters are computed if you want to use them in components
  public userName: Ref<string>;

  constructor() {
    this.loaded = ref(false);
    initializeFromServer()
      .then(info: SomeTypeWithSettingsFromServer) => {
        this.userId = ref(info.userId);
        this.userFirstName = ref(info.userFirstName);
        this.userLastName = ref(info.userLastName);

        this.userName = computed<string>(() => 
          return this.userFirstName.value + ' ' + this.userLastName.value;
        }
     }
      .catch(/* do some error handling here */);
  }

  private initializeFromServer(): Promise<SomeTypeWithSettingsFromServer> {
    return axios.get('url').then((response) => response.data);
  }

  // This is a getter that you don't need to be reactive
  public fullName(): string {
     return this.userFirstName.value + ' ' + this.userLastName.value;
  }

  public switchToClub(clubId: number): Promise<any> {
    return axios.post('switch url')
      .then((data: clubInfo) => {
        // do some processing here
      }
      .catch(// do some error handling here);
  }
}

export appModule = new AppClass();

어디서든 appModule에 접속하고 싶을 때는 다음과 같이 해야 합니다.

import { appModule } from 'AppStore';

...
if (appModule.loaded.value) {
  const userName = appModule.fullName();
}

또는 compositionApi 기반 컴포넌트에 있습니다.이것이 mapActions 등을 대체하는 것입니다.

<script lang="ts">
import { defineComponent } from '@vue/composition-api';
import { appModule } from '@/store/appStore';
import footer from './footer/footer.vue';

export default defineComponent({
  name: 'App',
  components: { sfooter: footer },
  props: {},
  setup() {
    return { ...appModule }
  }
});
</script>

템플릿에서 userId, userFirstName, userName 등을 사용할 수 있게 되었습니다.

도움이 됐으면 좋겠다.

방금 계산한 게터를 추가했습니다.나는 그것이 정말 필요한지 시험해 볼 필요가 있다.템플릿 내에서 fullName()만 참조할 수 있고 fullName()은 다른 참조의 .value 변수를 참조하기 때문에 fullName은 참조 자체가 될 수 있습니다.하지만 나는 먼저 그것을 확인해야 한다.

언급URL : https://stackoverflow.com/questions/54127423/vuex-module-decorator-modifying-state-inside-an-action

반응형