Vue.js 从服务器接收数据的Vue
我只是想说我不久前就熟悉了vue。Vue.js 从服务器接收数据的Vue,vue.js,async-await,store,vuex,Vue.js,Async Await,Store,Vuex,我只是想说我不久前就熟悉了vue。 现在我有个问题 我从服务器获取数据 //商店 从“../services/PostService”导入PostService export default { state: { posts: [], }, actions: { async getPost() { const response = await PostService.fetchPosts(); console.log(response.dat
现在我有个问题 我从服务器获取数据 //商店
从“../services/PostService”导入PostService
export default {
state: {
posts: [],
},
actions: {
async getPost() {
const response = await PostService.fetchPosts();
console.log(response.data.posts);
this.posts = response.data.posts
}
}
}
有一个数据数组和对服务器的请求。
在响应中
,数据来自
// vue component
<template>
<section class="posts--wrap">
<div class="posts wrapper">
<h1>Posts</h1>
<div
class="posts__item--wrap"
v-if="this.allPosts.length"
>
<h3>List of posts</h3>
<div
v-for="(post, index) in allPosts"
:key="index"
class="posts__item">
<h3 class="posts__item-title">{{post.title}}</h3>
<p class="posts__item-text">{{post.description}}</p>
</div>
</div>
<div
v-else
class="posts__item-error"
>
<h3>There are no posts ... Lets add one now!</h3>
<router-link tag="div" :to="{name: 'Add'}">
<a>Add new post ;)</a>
</router-link>
</div>
</div>
</section>
</template>
<script>
import { mapState } from 'vuex';
import { mapActions } from 'vuex';
export default {
name: 'PostPage',
data () {
return {
}
},
computed: mapState({
allPosts: state => state.posts.posts
}),
methods: {
...mapActions({
getAllPosts: 'getPost'
})
},
mounted() {
console.log(this.allPosts);
this.getAllPosts();
}
}
</script>
您的操作
getPost
出错,通过操作更改状态的正确方法是使用actioncontext
参数提交变异,如下所示:
...
mutations: {
setPosts(state, posts) {
state.posts = posts;
},
},
actions: {
async getPost(context) {
/* ... */
context.commit('setPosts', response.data.posts);
}
},
...
.我们可以看看响应的console.log显示了什么吗。@Andrew1325我更新了问题您的响应对象没有名为data的属性。看看API,我的意思是你必须知道响应对象的结构。
...
mutations: {
setPosts(state, posts) {
state.posts = posts;
},
},
actions: {
async getPost(context) {
/* ... */
context.commit('setPosts', response.data.posts);
}
},
...