【问题标题】:Cannot get Vuex state on async created无法在异步创建时获取 Vuex 状态
【发布时间】:2020-11-16 21:08:09
【问题描述】:

我有以下 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 的各种组合,结果要么出错,要么没有区别。

【问题讨论】:

    标签: vue.js vuex vuex-modules vue-property-decorator


    【解决方案1】:

    您缺少一些步骤。让我们调用 Vuex 模块,VuexModule

    在你的 VuexModule 中,添加一个命名空间名称

    @Module({ namespaced: true, name: 'Post' }) // add name

    import { namespace } from 'vuex-class';
    import { getModule } from 'vuex-module-decorators';
    
    import VuexModule from '@/store/modules/vuexmodule.ts'; //module which has 'Post' as namespace
    
    const postStore = namespace('Post')
    
    let vuexModule: VuexModule;
    
    export default class HelloWorld extends Vue {
      async created() {
        vuexModule = getModule(VuexModule, this.$store);
        await vuexModule.refreshPost();
      }
    }

    您可以在这个优秀的article中了解更多信息

    【讨论】:

    • 感谢您的回答。我之前已经包含了命名空间名称,但我得到了一个不同的错误,并按照this github issue 的建议删除了它
    • 成功了吗?如果是这样,我很高兴听到它。请接受我的回答。
    • 抱歉不清楚 - 它确实似乎已经解决了先前的命名空间问题,但尚未解决页面加载问题
    • 嗨,@ste-fu,您是否按照我提出的步骤进行操作?请发布您的代码。我看不出它为什么不能工作。
    猜你喜欢
    • 2021-08-02
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 2019-03-20
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多