1

我正在尝试使用 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 还是很陌生。

4

1 回答 1

6

你的主要问题是你的突变。

突变是对状态的同步更新,因此您正确地从操作(处理异步请求的地方)调用它,但您没有将突变传递给任何放置在状态中的东西。突变接受参数,所以你的LOAD_CATALOG突变会接受catalogData,即

mutations: {
    LOAD_CATALOG (state, catalogData) {
        state.catalog = catalogData
    }
},

此外,如果您使用 Vue 2 的 vue 资源,那么您应该将响应的主体传递给突变,即

getCatalog({commit}){
    Vue.http.get('https://example.net/api.json').then(response => {
        commit('LOAD_CATALOG', response.body[0].threads)
    });
}

下一个问题是您不需要getter, getter 允许我们计算派生状态,您不需要它们只是为了返回现有状态(在您的案例目录中)。您可以使用 getter 的一个基本示例是将 1 添加到存储在 state 中的计数器,即

getters: {
    counterAdded: state => state.counter + 1,
}

完成这些更改后,事情看起来会更像下面这样:

//store.js

state: {
    catalog: []
},

actions: {
    getCatalog({commit}){
        Vue.http.get('https://example.net/api.json').then(response => {
            commit('LOAD_CATALOG', response.body[0].threads)
        });
    }
},

mutations: {
    LOAD_CATALOG (state, catalogData) {
        state.catalog = catalogData
    }
},

//component.vue

created () {
    this.$store.dispatch('getCatalog')
},

computed: {
    catalog () {
        return this.$store.state.catalog
    }
}
于 2016-11-18T17:08:46.417 回答