代码之家  ›  专栏  ›  技术社区  ›  Alex Marek

Vuex和axios,初始页面加载时未显示远程内容

  •  0
  • Alex Marek  · 技术社区  · 7 年前

    我的头撞了这一天左右,现在需要你来救我。

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

    问题是我的数据在加载时没有显示,在呈现时引发了一个错误:“TypeError:无法读取未定义的属性‘title’”, 。一旦我开始更改代码,webpack在保存时进行热加载,就会显示内容。看起来数据在页面加载时不可用。我无法用我目前的知识来解决这个问题。

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

    这是代码。

    职位。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>
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Ru Chern Chong ABHINAV    7 年前

    您有posts的miss类型mapState,但没有posts属性。你家的L18-19。vue文件 在页面之间存在类型错误解释,如 Array 和内容/标题为 String .家的L4-5层。vue文件

    家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>
    
        2
  •  0
  •   Alex Marek    7 年前

    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>
    

    谢谢