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!: () => any
static 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
'programing' 카테고리의 다른 글
Vue2 - 오류: CSS 문자열 대신 PostCSS가 정의되지 않았습니다. (0) | 2022.08.27 |
---|---|
[Vue warn] :알 수 없는 사용자 지정 요소: ..." vuetify UI 구성 요소를 vue-cli-plugin-vuetify와 함께 사용하는 경우 오류 발생 (0) | 2022.08.27 |
함수의 함수 포인터 및 주소 (0) | 2022.08.19 |
템플릿에서 직접 vuex 상태 사용/수정 (0) | 2022.08.19 |
Link-Time Optimization(LTO; 링크타임 최적화)을 사용하지 않는 이유가 있습니까? (0) | 2022.08.19 |