Vuex getter 不响应状态变化
Vuex getter does not react on state change
我有一个代码需要从 Vuex 存储中获取一些处理后的值。所以我写了 getter 应该 return 处理值。代码如下所示:
mediaSettings: (state) => {
const timestamps = [];
const events = [];
state.media.forEach( medium => {
if( !medium.settings || !medium.settings.dates ) return;
medium.settings.dates.forEach( dateRange => {
if( !dateRange.date_from || !dateRange.date_to ) return;
const from = new Date( dateRange.date_from );
const to = new Date( dateRange.date_to );
while ( from <= to ) {
if( timestamps.includes(from.getTime()) ) {
from.setDate( from.getDate() + 1 );
continue;
}
events.push({
date: new Date( from.getTime() ), // Need Date clone via new Date().
mediumId: medium.id,
});
timestamps.push( from.getTime() );
from.setDate( from.getDate() + 1 );
};
});
});
return events;
}
这是改变值的突变:
SET_MEDIA_SETTINGS(state, payload) {
state.media.forEach( medium => {
if( medium.id === payload.media_id ) {
medium.settings = { timeMode: payload.mode, dates: payload.dates, times: payload.times };
}
});
},
问题是 Vuex 在 state.media[].settings.dates[] 值改变时没有反应。更改应该发生在 state.media[] 级别。我该如何解决?此问题的解决方法是什么?感谢您的帮助。
这个问题的解决方案是使用 Vue set() 方法来更改 mutation 中的值。
代码在这里:
SET_MEDIA_SETTINGS(state, payload) {
state.media.forEach( (medium, index) => {
if( medium.id === payload.media_id ) {
medium.settings = { timeMode: payload.mode, dates: payload.dates, times: payload.times };
this._vm.$set(state.media, index, {...medium});
}
});
},
我有一个代码需要从 Vuex 存储中获取一些处理后的值。所以我写了 getter 应该 return 处理值。代码如下所示:
mediaSettings: (state) => {
const timestamps = [];
const events = [];
state.media.forEach( medium => {
if( !medium.settings || !medium.settings.dates ) return;
medium.settings.dates.forEach( dateRange => {
if( !dateRange.date_from || !dateRange.date_to ) return;
const from = new Date( dateRange.date_from );
const to = new Date( dateRange.date_to );
while ( from <= to ) {
if( timestamps.includes(from.getTime()) ) {
from.setDate( from.getDate() + 1 );
continue;
}
events.push({
date: new Date( from.getTime() ), // Need Date clone via new Date().
mediumId: medium.id,
});
timestamps.push( from.getTime() );
from.setDate( from.getDate() + 1 );
};
});
});
return events;
}
这是改变值的突变:
SET_MEDIA_SETTINGS(state, payload) {
state.media.forEach( medium => {
if( medium.id === payload.media_id ) {
medium.settings = { timeMode: payload.mode, dates: payload.dates, times: payload.times };
}
});
},
问题是 Vuex 在 state.media[].settings.dates[] 值改变时没有反应。更改应该发生在 state.media[] 级别。我该如何解决?此问题的解决方法是什么?感谢您的帮助。
这个问题的解决方案是使用 Vue set() 方法来更改 mutation 中的值。 代码在这里:
SET_MEDIA_SETTINGS(state, payload) {
state.media.forEach( (medium, index) => {
if( medium.id === payload.media_id ) {
medium.settings = { timeMode: payload.mode, dates: payload.dates, times: payload.times };
this._vm.$set(state.media, index, {...medium});
}
});
},