【问题标题】:Getters in vuex is being called before actions在动作之前调用 vuex 中的吸气剂
【发布时间】:2022-01-20 14:33:55
【问题描述】:

我正在使用 vuex,在我的设置中我先调用 dispatch 然后调用 getter。当我刷新页面时,总是首先调用 getter,但我不确定如何使用 async await 进行更改,因此只有在调用操作时才会触发 getter。

这是我在 .vue 文件中的设置

setup(props: any, context: any) {
    const store: any = useStore()
    store.dispatch('teams/getTeams')
    let teams = computed(() => store.getters['teams/teams']) as any;
}

这是我的 actions.ts 文件

    import Http from "@/helpers/Http";
    
    export const actions = {
        async getTeams({ commit, dispatch}: any) {
            const http = new Http();
            const response = await http.get(`/api/teams`)
            commit('setTeams', response)
        }
    }

Here is the Http.ts


import axios from 'axios'

export default class Http {    
  async put(url: string, data: any) {
    const response = await axios.put(url, data)
    if(response.data){
      return response.data 
    }else{
      return response.status;
    }
  }
}

这里是 mutation.ts

export const mutations = {
  setTeams(state: any, teams: any) {
    state.teams = teams
  }
}

这里是 getters.ts

export const getters = {
  teams: (state: any): any => {
    console.log("In getters")
    return state.teams
  }
}

我要更改什么,以便仅在调度调用之后触发 getters 调用?

【问题讨论】:

    标签: async-await vuex vuejs3


    【解决方案1】:

    动作是异步的。如果您想等待解决操作,您可以使用异步等待。看这个例子(没有组合 API):

    “组件.vue”

    methods: {
        async getTeam(){
           await this.$store.dispatch('teams/getTeams')
           let teams = computed(() => store.getters['teams/teams']) as any;
        }
    }
    
    

    如果您想捕获 api 响应,可以从操作中返回它。

    “组件.vue”

    methods: {
        async getTeam(){
           data = await this.$store.dispatch('teams/getTeams')
           ....
        }
    }
    
    

    动作示例,例如“store/teams.js”

    export const actions = {
       async getTeams(){
            const http = new Http();
            const response = await http.get(`/api/teams`)
            return response
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-18
      • 2017-10-11
      • 2021-06-01
      • 2011-05-28
      • 1970-01-01
      • 2019-11-26
      • 2019-11-17
      • 2011-06-11
      • 2021-03-01
      相关资源
      最近更新 更多