【问题标题】:Vuex and axios, remote content not showing on initial page loadVuex 和 axios,远程内容未在初始页面加载时显示
【发布时间】:2018-10-15 16:30:10
【问题描述】:

我已经用头撞这个了一天左右,现在需要你来救我。

我正在构建一个 rest-api 驱动的 vue.js 站点。我正在使用 vuex-rest-api 从 wordpress 的副本中获取数据,然后将其输出到页面上。

问题是我的数据在加载时不显示,在渲染中抛出错误错误:“TypeError:无法读取未定义的属性'title'”, .一旦我开始对代码进行更改,webpack 会在保存内容显示时进行热重载。看起来数据在页面加载时不可用。我无法用我目前的知识解决这个问题。

我为 getPosts() 尝试了不同的生命周期挂钩(例如 beforeCreated()),但没有帮助。

这里是代码。

posts.js 从“vuex-rest-api”导入 Vapi

const pages = new Vapi({
  baseURL: "http://localhost:8888/wp-json/wp/v2",
  state: {
    pages: []
  }
})
.get({
  action: "getPosts",
  property: "pages",
  path: "/pages"
})
.getStore()


export default pages

主页.vue

<template>
    <div class="container header header--home">

    <h2 v-for="item in title" :key="item.id" v-html="item"></h2>
    <p v-for="item in content" :key="item.id" v-html="item"></p>

</div>
</template>

<script>

import { mapState, mapActions } from 'vuex'
export default {
  created() {
    this.getPosts()
  },
  computed: mapState({
    content: state => state.posts.pages[0].content,
    title: state => state.posts.pages[0].title,
  }),
  methods: {
    ...mapActions([
      "getPosts",
    ])
  }
}

</script>

【问题讨论】:

    标签: rest vue.js axios vuex


    【解决方案1】:

    Ru 上面建议的很棒的东西。

    稍微调整了代码:

    computed: mapState({
        pages: state => state.posts.pages,
    }),
    

    不知何故,我正在使用的 vuex-rest-api 需要提及这些帖子。

    另外,为了从 wordpress rest-api 中获取正确的数据,我不得不稍微调整一下循环:

    <div class="col-sm" v-for="item in pages" :key="item.id">
        <h2 v-html="item.title.rendered"></h2>
        <p v-html="item.content.rendered"></p>
    </div>
    

    谢谢!

    【讨论】:

      【解决方案2】:

      您错过了带有帖子的 mapState 类型,但没有帖子属性。您的 Home.vue 文件的 L18-19 在Array 的页面和String 的内容/标题之间存在类型的错误解释。您的 Home.vue 文件的 L4-5

      首页.vue

      <template>
         <div class="container header header--home">
            <div v-for="item in pages" :key="item.id">
               <h2 v-html="item.title"></h2>
               <p v-html="item.content"></p>
            </div>
      
         </div>
      </template>
      
      <script>
         import { mapState, mapActions } from 'vuex'
         export default {
            created() {
               this.getPosts()
            },
            computed: {
              ...mapState({
                pages: state => state.pages
              })
            },
            methods: {
               ...mapActions([
                  "getPosts",
               ])
            }
         }
      </script>
      

      【讨论】:

        猜你喜欢
        • 2010-11-17
        • 2019-03-06
        • 1970-01-01
        • 2014-02-23
        • 2012-08-21
        • 2020-12-04
        • 1970-01-01
        • 2013-05-08
        • 1970-01-01
        相关资源
        最近更新 更多