我的应用工作流程是从API后端获取一些数据,并在LokiJS的帮助下写入客户端存储。我在客户端集合中有数千个数据。对于我的应用程序的状态管理,我使用Vuex。
这就是问题所在。当我提交对Vuex状态的更改时,它也会更改LokiJS存储中的数据。我怎么才能避免这种情况?
我有Vuex操作从LS (lokijs存储)获取用户。
getStudentByClass({ state, commit }) {
const stds = students.collection.find({ class_id: state.classId });
commit('setStudents', stds);
}
selectStudent(state, index) {
const student = state.students[index];
Vue.set(student, 'selected', !student.selected);
}Vuex突变
setStudents(state, students) {
state.students = students
}如上所示;使用selectStudent函数,我在Vuex存储上更改了我的学生选择的属性,但在LS上也发生了变化。
原始LS数据如下所示
$loki: 63
class_id: 5
color: "green"
id: 248
meta: Object
name: "John Doe"
point: 100
teacher: 0
updated_at: "2017-01-24 10:00:34"
username: "johdoe"LS数据变化
$loki: (...)
class_id: (...)
color: (...)
id: (...)
meta: (...)
name: (...)
point: (...)
selected: true <--------------- here
teacher: (...)
updated_at: (...)
username: (...)
__ob__: Observer
get $loki: function reactiveGetter()
set $loki: function reactiveSetter(newVal)
// skipped发布于 2017-03-11 12:05:06
在JS中,对象是通过引用传递的,所以在vuex中更改对象也会在loki中更改它们。这没什么不寻常的。
如果您不想这样做,那么在将结果传递给vuex之前,应该使用像clone-deep这样的包来克隆loki的结果(当您使用它时,lodash也有这样的函数)。
https://stackoverflow.com/questions/42727331
复制相似问题