【发布时间】:2017-04-02 13:10:30
【问题描述】:
我正在尝试使用 vuex 将一个数组从我的 api 拉到一个组件中,但我很茫然,并且可能在尝试这个时不知所措。通过直接从组件访问 api,我将其设置为这样,这很好:
data () {
return {
catalog:[],
}
},
created() {
this.$http.get('https://example.net/api.json').then(data => {
this.catalog = data.body[0].threads;
})
}
作为参考,json 看起来类似于:
[{
"threads": [{
"no: 12345,
"comment": "comment here",
"name": "user"
}, {
"no: 67890,
"comment": "another comment here",
"name": "user2"
}],
//this goes on for about 15 objects more in the array
"page": 0
}]
当我将这一切都转移到商店时,我对如何真正做到这一点失去了把握。我以前用过 vuex,只是从来没有用过 vue-resource。
//store.js
state: {
catalog: []
},
actions: {
getCatalog({commit}){
Vue.http.get('https://example.net/api.json').then(response => {
commit('LOAD_CATALOG', response.data.data)
});
}
},
mutations: {
LOAD_CATALOG (state) {
state.catalog.push(state.catalog)
}
},
getters: {
catalog: state => state.catalog,
}
//component.vue
created () {
this.$store.dispatch('getCatalog')
},
computed: {
catalog () {
return this.$store.getters.catalog
}
}
我知道这是错误的,我收到了最大调用堆栈大小错误。当我把所有东西都放在商店里时,我怎样才能得到与上面示例 (this.catalog = data.body[0].threads;) 中发布的相同的结果?
如果有任何需要澄清的地方,请告诉我!我对使用 Vue 2.0 还是很陌生。
【问题讨论】:
标签: vue.js vuejs2 vuex vue-resource