Vue3 的 onMounted 钩子中带有异步的 Pinia 方法未同步执行 - 我错过了什么?

问题描述 投票:0回答:1

我在 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,
  };
});

async-await vuejs3 pinia
1个回答
0
投票

你需要重写

getComments
:

const getComments = async (storeId) => {
    const result = await axiox.get(`/stores/${storeId}?_embed=comments`);
    comments.value = result.data.comments;
    store.value = result.data;
};
© www.soinside.com 2019 - 2024. All rights reserved.