我正在尝试使用 pinia 和 nuxt 从本地数据中获取数据,但无法接缝以获得终点,我的代码有什么问题?



我试图从本地数据与pinia和next获取数据,它不能接缝得到终点,我的代码有什么问题?

我是Vue, next和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;
},
},
});

# app.vue

<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服务器和django rest框架没有结果,但当我在帖子中添加数据:[]它正确地显示在html中的数据。如何才能成功地从端点获取数据?

主要问题是您试图与之交互的假端点。

尝试这个端点https://my-json-server.typicode.com/typicode/demo/posts,它适合于测试目的!

或者这个端点https://dummyjson.com/posts有很多信息可以交互!

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

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

这个变魔术了。

最新更新