【问题标题】:Using Vue-Resource in Vuex store; getting maximum call stack size error在 Vuex 商店中使用 Vue-Resource;获取最大调用堆栈大小错误
【发布时间】: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


    【解决方案1】:

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

    突变是对状态的同步更新,因此您正确地从操作(处理异步请求的地方)调用它,但您没有传递突变以放置在状态中。突变接受参数,因此您的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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-05
      • 1970-01-01
      • 2021-12-24
      • 2012-08-14
      • 2016-10-14
      • 2011-08-31
      • 1970-01-01
      • 2015-08-22
      • 2017-05-23
      相关资源
      最近更新 更多