javascript - 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)) 没用。
我在这里做错了什么?
解决方案
一个动作应该返回一个 的承诺undefined
,它不正确地使用它就像this.$store.dispatch("fetchUsers").then(res => ...)
.
派发操作后需要访问商店:
this.$store.dispatch("fetchUsers").then(() => {
this.paginate();
});
推荐阅读
- python-3.x - Tensorflow 中的一些张量操作
- c# - 定时器在全局文件中的 iis 服务器上无法正常工作
- sql - SQL:ORDER BY 语句中的嵌套大小写
- bash - Travis 构建的意外标记“else”附近的语法错误
- ms-word - 如何在单个 Microsoft Word 文档中存储不同的视图?
- excel - VBA用公式交换行范围忽略单元格
- javascript - vue-i18n 自定义块的动态源
- oracle - PL/SQL 甲骨文。实现 IS_CONTAINED 运算符的最佳方法
- c++ - 从函数打印 CLI 帮助消息后,我应该如何干净地退出 C++ 程序?
- android - 禁用状态栏下拉 - API 版本的差异?