首页 > 解决方案 > 如何在 Vuex 的操作中使用 axios 获取 RestAPI 数据?

问题描述

我试图获取 RestAPI 数据以在 Vuex 系统的操作中使用 axios 并在组件中显示该信息。所以我尝试使用测试 API 示例制作小应用程序,但出现错误。

我使用了那个测试 API。它包括 5 个键,例如“postId”、“id”、“name”、“email”、“body”。就我而言,我只想向我的组件显示“id”信息。但错误消息说“TypeError:无法读取未定义的属性'id'”

我的 Vuex 代码在 store/customer.ts 下面

    import { MutationTree, ActionTree, GetterTree } from "vuex";
import { RootState } from "../types";
import { Customer } from "../types/customer";
import axios from "axios";

interface State {
  customer: Customer;
}
export const state = () => ({
  customer: []
});
export const getters: GetterTree<State, RootState> = {
  customer: (state: State) => state.customer
};
export const mutations: MutationTree<State> = {
  setCustomer(state: State, customer: Customer) {
    state.customer = customer;
  }
};
export const actions: ActionTree<State, RootState> = {
  getCustomerInfo: async ({ commit }) => {
    const data = await axios.get(
      "https://jsonplaceholder.typicode.com/posts/1/comments"
    );
    commit("setCustomer", data.data.customer);
  }
};
export default {state,getters,mutations,actions}

我在直接类型中定义了 RootState 和 Customer 的类型。我真的不明白如何通过 acitons 将数据设置为 setCustomer 突变。类型/index.ts

export interface RootState {}

类型/customer.ts

    export interface Customer {
    postId?: number;
    id?: number;
    name?: string;
    email?: string;
    body?: string;
  }

和 test.vue 下面的我的 vue 组件

<template>
  <div>
    <Counter />
    <p>vuex test</p>
    <p>{{ customer.id }}</p>
  </div>
</template>
<script lang="ts">
import { Component, namespace, Vue } from 'nuxt-property-decorator'
import { Customer } from '~/types/customer'
const SCustomer = namespace('customer')

@Component({})
export default class extends Vue {
  @SCustomer.Action getCustomerInfo!: Function
  @SCustomer.State customer!: Customer

  async created() {
    await this.getCustomerInfo()
  }
}
</script>

我真的很懂vuex!有人可以给我建议吗?

标签: typescriptvue.jsnuxt.js

解决方案


在该状态下,确保请求成功并且在提交突变之前您有数据。您需要一个 getter 才能访问状态数据。确保您可以访问状态 Actions,否则,您将需要 mapActions。希望这会有所帮助。

import { MutationTree, ActionTree, GetterTree } from "vuex";
import { RootState } from "../types";
import { Customer } from "../types/customer";
import axios from "axios";

interface State {
  customer: Customer;
}
export const state = () => ({
  customer: []
});
export const getters: GetterTree<State, RootState> = {
  customer: (state: State) => state.customer
};
export const mutations: MutationTree<State> = {
  setCustomer(state: State, customer: Customer) {
    state.customer = customer;
  }
};
export const actions: ActionTree<State, RootState> = {
  getCustomerInfo: async ({ commit }) => {
    const data = await axios.get(
      "https://jsonplaceholder.typicode.com/posts/1/comments"
    ).then((response) => {
        if(response.status === 'success'){
            commit("setCustomer", data.data.customer);
        }
   })
  };
};
export default {state, getters, mutations, actions}

在 Vue 实例中

<template>
  <div>
    <Counter />
    <p>vuex test</p>
    <p>{{ customer.id }}</p>
  </div>
</template>
<script lang="ts">
import { Component, namespace, Vue } from 'nuxt-property-decorator'
import { Customer } from '~/types/customer'
const SCustomer = namespace('customer')

@Component({})
export default class extends Vue {
  @SCustomer.Action getCustomerInfo!: Function
  @SCustomer.State customer!: Customer

    computed: {
       ...mapGetters(['customer'])
    },

    created() {
        this.getCustomerInfo()
    }
}
</script>

推荐阅读