programing

vue + Typescript 클래스 구성 요소와 mapActions를 사용하는 방법

yoursource 2022. 8. 27. 13:59
반응형

vue + Typescript 클래스 구성 요소와 mapActions를 사용하는 방법

올바른 사용법을 알고 싶습니다....mapActions([])Typescript vue 클래스 컴포넌트 내에 있습니다.

이렇게 하는 거예요.

<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";
import { mapActions } from "vuex";

@Component
export default class UsersAdd extends Vue {
  userName: string = "";

    ...mapActions(["newUser"]) /*mapAction from vuex */
  addUser() {
    console.log("...adding new user");
    this.newUser(this.userName);
  }
}
</script>

이게 안 먹히니까...

Javascript에서는 이렇게 합니다.

methods:{
  ...mapActions(["newUser"])
}

Typescript 클래스 컴포넌트로 어떻게 하면 좋을까요?

편집: 이렇게 시도했지만 아직 작동하지 않습니다.

@Component({
  methods: {
    ...mapActions(["newUser"]) /*mapAction from vuex */
  }
})
export default class UsersAdd extends Vue {
  userName: string = "";

  addUser() {
    console.log("...adding new user");
    this.newUser(this.userName);
  }
}

또 다른 종속성(vuex 클래스)을 도입하고 싶지 않은 경우.스토어의 액션을 다음과 같이 Typescript의 컴포넌트에 매핑할 수 있습니다.

@Component({
  computed: {
    ...mapActions({
      someLoadDataAction: "someLoadDataAction"
    })
  }
})
export default class HelloWorld extends Vue {
  someLoadDataAction!: () => any;

  mounted() {
    console.log(this.someLoadDataAction);
  }
}

열쇠는 이것을 추가하는 것이다.someLoadDataAction!: () => anystatic type의 경우 Typescript를 확인합니다.예를 들어 다음과 같이 정의된 함수 유형이 있습니다.() => any단, 의 액션에서 실제 반환 타입으로 변경할 수 있습니다.vuex가게.

작업 주석을 사용하여 이 작업을 수행할 수 있습니다.인스톨npm install --save vuex-class

import { Action } from 'vuex-class'

@Component()
export default class UsersAdd extends Vue {
  userName: string = "";

  @Action('newUser')
  newUser!: (newUser: string) => void
  addUser() {
    console.log("...adding new user");
    this.newUser(this.userName);
  }
}

다른 방법으로는 커스텀데코레이터를 사용하면 컴포넌트의 메서드를 vuex 스토어의 메서드로 대체할 수 있습니다.

function VuexAction(moduleName: string): any {
  return createDecorator((options: any, key: string) => {
    if (!options.methods) options.methods = {};
    options.methods[key] = function wrapperMethod(...args: any[]) {
      return this.$store._actions[`${moduleName}/${key}`][0](...args);
    };
  });
}

데코레이터는 다음과 같이 사용할 수 있습니다.

@Component
export default class SomeComponent extends Vue {
  @VuexAction("vuexModuleName") vuexModuleActionName!: () => void;

  async doStuff () {
    this.vuexModuleActionName();
  }
}

이 아이디어는 커스텀 데코레이터에 관한 문서를 기반으로 합니다.

https://class-component.vuejs.org/guide/custom-decorators.html

커스텀 vuex getter 데코레이터:

https://github.com/vuejs/vue-class-component/issues/56#issuecomment-272604193

기타 옵션으로 vuex-module-decorator를 사용할 수 있습니다.이것에 의해, 서포트가 향상됩니다.typescript코드를 줄입니다.

설치하다

npm install -D vuex-module-decorators

스토어/index.ts

import { Action, getModule, Module, Mutation, VuexModule } from "vuex-module-decorators";
import store from "..";

// define Mutations name
enum Mutations {
  NEW_USER_NAME = "NEW_USER_NAME"   
}

// name: module name
// dynamic: true,dynamic create module
// namespaced: true,using namespaced
// store: your root store/index.ts
@Module({ name: 'UserStore', dynamic: true, namespaced: true, store })
export default class UserStore extends VuexModule {
  // state
  userName = '';

  // mutation
  @Mutation
  [Mutations.NEW_USER_NAME](userName: string) {
    this.userName = userName;
  }

  // action
  @Action
  newUser(userName: string) {
    this.context.commit(Mutations.NEW_USER_NAME, userName);
  }
}

// use getModule to safe get instance
export const userStore = getModule(UserStore);

UsersAdd(사용자추가표시하다

import { userStore } from "@/store/modules/user";
@Component()
export default class UsersAdd extends Vue {
  userName: string = "";
   
  addUser() {    
    console.log("...adding new user");     
    userStore.newUser(this.userName);
  }
}

언급URL : https://stackoverflow.com/questions/60099323/how-to-use-mapactions-with-vue-typescript-class-component

반응형