首页 > 解决方案 > Vue.js Typescript 我使用 getter 获取数据,但无法在方法中访问它

问题描述

我是 vuex 的 Typescript 新手。我只是想从后端获取用户列表。放在店里。我声明了自定义用户类型

export interface User {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
}

在我的 vuex.d.ts 文件中,我声明了 store 模块,如:

import { Store } from "vuex";
import { User } from "./customTypes/user";

declare module "@vue/runtime-core" {
  interface State {
    loading: boolean;
    users: Array<User>;
  }

  interface ComponentCustomProperties {
    $store: Store<State>;
  }
}

在我的商店中,我成功获取了用户并提交了状态:

import { createStore } from "vuex";
import axios from "axios";
import { User, Response } from "./customTypes/user";

export default createStore({
  state: {
    users: [] as User[], // Type Assertion
    loading: false,
  },
  mutations: {
    SET_LOADING(state, status) {
      state.loading = status;
    },
    SET_USERS(state, users) {
      state.users = users;
    },
  },
  actions: {
    async fetchUsers({ commit }) {
      commit("SET_LOADING", true);
      const users: Response = await axios.get(
        "http://localhost:8000/api/get-friends"
      );
      commit("SET_LOADING", false);
      commit("SET_USERS", users.data);
    },
  },

  getters: {
    userList: (state) => {
      return state.users;
    },
    loadingStatus: (state) => {
      return state.loading;
    },
  },
});

我设置了 getter,我觉得我不需要设置 getter 来返回状态,但这是我可以访问组件中数据的唯一方法。请告知是否有更好的方法来做到这一点。在我的组件中,我访问了如下数据:

  <div class="friends">
    <h1 class="header">Friends</h1>
    <loading v-if="loadingStatus" />

    <div v-else>
      <user-card v-for="user in userList" :user="user" :key="user.id" />
      <pagination />
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { mapGetters } from "vuex";
import { User } from "../store/customTypes/user";
=import UserCard from "../components/UserCard.vue";
import Loading from "../components/Loading.vue";
import Pagination from "../components/Pagination.vue";

export default defineComponent({
  name: "Friends",
  components: {
    UserCard,
    Loading,
    Pagination,
  },
  static: {
    visibleUsersPerPageCount: 10,
  },
  data() {
    return {
      users: [] as User[],
      currentPage: 1,
      pageCount: 0,
    };
  },
  computed: {
    ...mapGetters(["loadingStatus", "userList"]),
  },
  mounted() {
    this.$store.dispatch("fetchUsers");
    this.paginate()
  },
  methods: {
    paginate () {
     // this.users = this.$store.state.users
      console.log(this.$store.state.users) 
      console.log(this.userList) 
    }

  }
});
</script>

现在,当我使用 getter 获取 userList 时,我成功获取了数据并显示在模板中。但是,当我想在方法中使用它时,安装组件时我无法访问它。我需要在方法中对其进行分页。所以我想我需要等到承诺得到解决,但我不知道如何解决。我试过这个。$store.dispatch("fetchUsers").then((res) => console.log(res)) 没用。

我在这里做错了什么?

标签: javascripttypescriptvue.jsvuex

解决方案


一个动作应该返回一个 的承诺undefined,它不正确地使用它就像this.$store.dispatch("fetchUsers").then(res => ...).

派发操作后需要访问商店:

this.$store.dispatch("fetchUsers").then(() => {
  this.paginate();
});

推荐阅读