我有以下 Vue 组件(基于 HelloWorld 示例)
<template>
<div class="hello">
<h1>Message: {{ post.title }} </h1>
<button @click="refreshPost">Refresh</button>
</div>
</template>
<script lang="ts">
import {Component, Vue, Prop, } from 'vue-property-decorator';
import {IPostModel} from "@/models/IPostModel";
import {namespace} from "vuex-class";
const postStore = namespace('Post')
@Component
export default class HelloWorld extends Vue {
@postStore.State
public post!: IPostModel
@postStore.Action
public refreshPost!: Promise<IPostModel>
async created(){
console.log("starting created");
await this.refreshPost;
console.log("finished created");
}
}
</script>
以及对应的Vuex模块
import axios from 'axios'
import { VuexModule, Module, Mutation, Action } from "vuex-module-decorators";
import { IPostModel } from "@/models/IPostModel";
@Module({namespaced: true })
class Post extends VuexModule{
public post: IPostModel = { id: -1, userId: -1, title: ''}
@Mutation
private setPost(newPost: IPostModel): void{
this.post = newPost;
}
@Action({rawError: true})
public async refreshPost(): Promise<IPostModel> {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
this.context.commit('setPost', response.data);
return response.data;
}
}
export default Post
当我单击刷新按钮时,调用 api 的代码工作正常,但似乎没有设置created
钩子上的状态,我不知道为什么。我尝试了 Promise & await & async 的各种组合,它要么出错,要么没有区别。