【问题标题】:Updating Vuex state changes LokiJS data, too. Why? Vuex / LokiJS更新 Vuex 状态也会改变 LokiJS 数据。为什么? Vuex / LokiJS
【发布时间】:2017-08-01 07:49:56
【问题描述】:

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

【问题讨论】:

    标签: vue.js vuex lokijs


    【解决方案1】:

    嗯,对象在 JS 中是通过引用传递的,所以在 vuex 中更改它们也会在 loki 中更改它们。这没有什么不寻常的。

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

    【讨论】:

    • 作为一种解决方法,我正在做JSON.parse(JSON.stringify(student))。但是现在使用 lodash 的 cloneDeep 效果很好: setStudents(state, students) { state.students = _.cloneDeep(students); },
    猜你喜欢
    • 1970-01-01
    • 2020-08-04
    • 2021-06-19
    • 2020-05-18
    • 2023-03-16
    • 2021-10-05
    • 2020-12-18
    • 2021-09-07
    • 1970-01-01
    相关资源
    最近更新 更多