Vue.js 打字稿 我使用 getter 获取数据,但无法在方法中访问它



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

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

在我的vexx .d.ts文件中,我声明了这样的存储模块:

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",然后((res) =比;Console.log (res))无法正常工作。

我在这里做错了什么?

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

需要在调度操作后访问存储:

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

最新更新