javascript 我尝试用pinia和nuxt从本地数据中获取数据,但是它不能缝合以获取端点,我的代码有什么问题?

kokeuurv  于 2023-01-16  发布在  Java
关注(0)|答案(2)|浏览(140)

我尝试用pinia和nuxt从本地数据中获取数据,但是它不能缝合以获取端点,我的代码有什么问题?
我是新的Vue,Nuxt和Pinia,我一直在遵循一些教程,但我不能从端点获得数据,这里是我的代码。
商店数量/blogStore.js

import { defineStore } from 'pinia';

export const usePostStore = defineStore('post', {
    state: () => ({
        posts: [],
        loading: false,
        error: null
    }),
    getters: {
        postCount: (state) => state.posts.length,
        draftPosts: (state) => state.posts.filter((post) => post.status === 'draft'),
        publishedPosts: (state) => state.posts.filter((post) => post.status === 'published'),
        isDraft: (state, id) => state.posts.find((post) => post.id === id)?.status === 'draft',
        truncatedPosts: (state) => state.posts.map((post) => post.content.substring(0, 20) + '...'),
    },
    actions: {
        async getPosts() {
            this.loading = true
            console.log(this.loading)
            const api = "http://localhost:3000/posts"
            const res = await fetch(api)
            console.log
            if (!res.ok) {
                this.error = res.statusText
                return;
            }
            const data = await res.json();
            this.posts = data;
            this.loading = false;
        },
    },
});

应用程序版本

<template>
<div v-if="store.loading">
    Loading ...
</div>
<div>
    <div> You have {{ store.postCount }} Blogs </div>
    <div v-for="post in store.posts" :key="post.id">
    <div>{{ post.title }}</div>

    <div>Views: {{ post.view_count }}</div>
    <br />
    </div>
</div>

</template>

<script setup>
import { usePostStore } from './stores/blogStore'
const store = usePostStore()

</script>

我尝试了几个后端,如本地json-server和django rest framework,但没有结果,但当我在帖子中添加数据时:[]它正确地显示了html中的数据。我如何成功地从端点获取数据?

5vf7fwbs

5vf7fwbs1#

主要问题在于您试图与之交互的假端点。
尝试此端点https://my-json-server.typicode.com/typicode/demo/posts,它适合用于测试目的!
或者这个端点https://dummyjson.com/posts有很多信息要交互!

yk9xbfzb

yk9xbfzb2#

在脚本设置中添加store.getPosts()会加载如下数据

<script setup>
import { usePostStore } from './stores/blogStore'
const store = usePostStore()
store.getPosts()

</script>

这就有魔力了。

相关问题