首页 文章

更新Vuex状态也会改变LokiJS数据 . 为什么? Vuex / LokiJS

提问于
浏览
3

我的应用工作流程是从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

1 回答

  • 2

    好吧,对象在JS中通过引用传递,因此在vuex中更改它们也会在loki中更改它们 . 没什么不寻常的 .

    如果你不想这样,你应该使用像 clone-deep 这样的包来克隆loki的结果,然后再将它传递给vuex(如果你使用它,lodash也有这样的功能) .

相关问题