[英]Vuex freezes on bulk mutations
I have the following Vuex store that I use to store chart objects retrieved from my backend using Axios. 我有以下Vuex商店,用于存储使用Axios从我的后端检索的图表对象。
const getters = {
charts( state ) { return _.without( state.charts, undefined ); },
chart( state ) { return id => state.charts.find( c => { return c.id === id; } ) }
}
const actions = {
getCharts( { commit, rootState } ) {
// Load data from server
return api.get( rootState.Laravel.api_url + '/chart' )
.then( ( response ) => {
// Store the returned data
_.forEach( response.data.data, function( chart ) {
commit( 'STORE_CHART', chart );
});
})
.catch( ( error ) => console.log( error ) );
}
}
const mutations = {
STORE_CHART( state, chart ) {
Vue.set( state.charts, chart.id, Object.freeze( chart ) );
}
}
The store works fine, but as soon as I open the VueDevtools and call getCharts() again, the whole browser freezes. 该商店工作正常,但只要我打开VueDevtools并再次调用getCharts(),整个浏览器就会冻结。 I guess this is because I'm updating the store in bulk and the devtools can't track all these changes (150 - 200 objects). 我想这是因为我正在批量更新商店,而devtools无法跟踪所有这些更改(150 - 200个对象)。
Is there something I'm doing wrong? 有什么我做错了吗? Is there a better way to bulk update objects in a Vuex store? 有没有更好的方法来批量更新Vuex商店中的对象?
Instead of commuting a mutation for each chart
in your forEach()
you can directly pass the response.data.data
as a payload to STORE_CHART` mutation and apply the forEach in the mutation itself 您可以直接将response.data.data
作为有效负载传递给STORE_CHART`变异,并将forEach应用于变异本身,而不是为forEach()
每个chart
换一个变异。
const actions = {
getCharts( { commit, rootState } ) {
// Load data from server
return api.get( rootState.Laravel.api_url + '/chart' )
.then( ( response ) => {
// Store the returned data
commit( 'STORE_CHART', response.data.data );
})
.catch( ( error ) => console.log( error ) );
}
}
const mutations = {
STORE_CHART( state, charts ) {
_.forEach( charts, function( chart ) {
Vue.set( state.charts, chart.id, Object.freeze( chart ) );
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.