Vue从服务器接收数据

时间:2018-11-09 21:26:41

标签: 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.data.posts);

      this.posts = response.data.posts

    }
  }
}

有一个数据数组和一个对服务器的请求。 数据来自response

// 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>

如果向state.posts添加内容,它将显示在页面上。

但是我不知道如何将数据从responseposts中 我寻求帮助或提示。 谢谢!

UPD 进行了更改,显示response

response.log

(2) [{…}, {…}]
0: {_id: "5be4bbfaad18f91fbf732d17", title: "Title post 1", description: "esxdfgdfghj"}
1: {_id: "5be490f930fba81a704867f6", title: "2312", description: "312312312"}
length: 2
__proto__: Array(0)

1 个答案:

答案 0 :(得分:1)

您在操作getPost中做错了,通过操作更改状态的正确方法是使用操作mutation参数来提交context,如下所示:

...
mutations: {
    setPosts(state, posts) {
        state.posts = posts;
    },
},
actions: {
    async getPost(context) {
        /* ... */
        context.commit('setPosts', response.data.posts);
    }
},
...

Read more about Vuex actions