【发布时间】:2018-03-25 05:07:32
【问题描述】:
我正在将 nuxtjs 用于服务器端渲染项目。我有一个 REST API,我想从那里更新 Vuex 商店并显示页面。 In the nuxtjs documentation for using Vuex store, it mentions using fetch api of the pages。所以我正在尝试获取 API 的文章列表并呈现页面。
Vuex 商店:
const createStore = () => {
return new Vuex.Store({
state: {
article_list: []
},
mutations: {
updateArticleList (state, payload) {
state.article_list = payload
console.log('article list length', state.article_list.length)
}
},
actions: {
mutateArticleList ({commit}, payload) {
api.get_articles()
.then((data) => {
commit('updateArticleList', data)
})
}
}
})
}
在 pages/index.vue:
<template>
<div>
<button @click="update">Update</button>
<p v-for="article in articles" :key="article.id">Article</p>
</div>
</template>
<script>
export default {
fetch ({store}) {
store.dispatch('mutateArticleList')
},
computed: {
articles () {
return this.$store.state.article_list
}
},
methods: {
update () {
this.$store.dispatch('mutateArticleList')
}
}
}
</script>
在控制台我可以看到商店的 article_list 已经更新了
console.log('article list length', state.article_list.length) // 16
但是在 index.vue 页面上,没有文章。即使在索引created 方法的控制台上,article_list 也是 0
console.log('index created length', this.$store.state.article_list.length) // 0
我在这里缺少什么?请你帮助我好吗。
【问题讨论】: