我在 onMounted 钩子中使用了 async 和 pinia 方法,但不同步执行代码。 当我尝试查看 {{ store }} 时,它不显示任何内容。请让我知道出了什么问题。谢谢你
page.vue(使用useCommentStore的页面)
<template>
{{ store }}
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { storeToRefs } from 'pinia';
import { useStoreStore } from '@/stores/useStoreStore';
const commentStore = useCommentStore();
const { comments, store } = storeToRefs(commentStore);
const {
getComments,
} = commentStore;
onMounted(async () => {
const route = useRoute();
await getComments(route.params.id);
console.log( store, comments);
});
<script>
useCommentStore.js
import axios from 'axios';
import { defineStore } from 'pinia';
import { ref } from 'vue';
export const useCommentStore = defineStore('comment', () => {
const comments = ref([]);
const store = ref({});
const getComments = (storeId) => {
axios.get(`/stores/${storeId}?_embed=comments`).then((res) => { comments.value = res.data.comments; store.value = res.data; });
};
return {
comments, getComments,
};
});
你需要重写
getComments
:
const getComments = async (storeId) => {
const result = await axiox.get(`/stores/${storeId}?_embed=comments`);
comments.value = result.data.comments;
store.value = result.data;
};