如何在axios请求后从加载中呈现组件

gijlo24d  于 12个月前  发布在  iOS
关注(0)|答案(1)|浏览(207)

在我的组件的脚本中,我用axios发出了一个get请求,但是在请求的结果准备好之前,组件就被渲染了。我该怎么做?顺便说一下,我尝试了onBeforeMount,并将axios.get放入同步函数中,并在onMounted内部调用它,这些都不起作用。

<template>
    <div class="p-4 m-4 bg-white rounded flex flex-col">
        <div>
            <h1 class="text-2xl text-gray-700">Projects</h1>
        </div>
        <div class="justify-center flex">
            <table class="table-auto justify-center">
                <thead>
                    <tr>
                        <th class="border px-4 py-2">ID</th>
                        <th class="border px-4 py-2">Name</th>
                        <th class="border px-4 py-2">Tasks</th>
                        <th class="border px-4 py-2">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="project in projects" :key="project.id">
                        <td>{{project.id}}</td>
                        <td>{{project.name}}</td>
                        <td>{{project.task_count}}</td>
                        <td>Actions</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>
<script setup>
    import {onMounted , ref} from 'vue';
    let projects = ref(null);

    onMounted(  ()=> {
        axios.get('/api/projects').then(res => {
            projects = res.data.data;
        });
    });
</script>
ghg1uchk

ghg1uchk1#

我认为唯一的问题是,你试图直接更新ref对象,但你应该更新它的内部属性 * 值 *,而不是...
尝试替换这个:

projects = res.data.data;

用这个:

projects.value = res.data.data;

文件:https://vuejs.org/guide/essentials/reactivity-fundamentals.html#ref
如果您希望组件只在 projects 可用时显示(非null),则可以将v-if添加到根元素:

<div
  v-if="projects"
  class="p-4 m-4 bg-white rounded flex flex-col"
>
  ...
</div>

如果可能有这样的情况,当来自API的响应是空数组(null,或类似的东西)时,您可能需要更新 v-if 中的条件(例如:projects?.length with Optional Chaining),但这真的取决于,你想如何处理等待响应和'空'响应.
文件:https://vuejs.org/guide/essentials/conditional.html#v-if

相关问题