【发布时间】: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>
【问题讨论】: