如何在Vuex中深度克隆状态并回滚?

2024-01-09

在 Vuex 中,我想拍摄树中对象属性的快照/克隆,修改它,然后可能回滚到以前的快照。

背景:
在应用程序中,用户可以在应用某些更改之前尝试它们。应用更改时,它们应该影响主 vuex 树。用户还可以单击“取消”放弃更改并返回到之前的状态。

Example:

state: {
  tryout: {},
  animals: [
    dogs: [
      { breed: 'poodle' },
      { breed: 'dachshund' },
    ]
  ]
}

用户进入“尝试”模式并更改一个品种poodle to chihuahua。然后,她决定放弃更改或应用更改。

state: {
  animals: [
    dogs: [
      { breed: 'poodle' },
      { breed: 'dachshund' },
    ]
  ],
  tryout: {
    animals: [
      dogs: [
        { breed: 'chihuahua' },
        { breed: 'dachshund' },
      ]
    ]
  }
}

Discard(回滚到之前的状态):

state: {
  animals: [
    dogs: [
      { breed: 'poodle' },
      { breed: 'dachshund' },
    ]
  ],
  tryout: {}
}

Apply(保存主 vuex 树中的更改):

state: {
  animals: [
    dogs: [
      { breed: 'chihuahua' },
      { breed: 'dachshund' },
    ]
  ],
  tryout: {}
}

有哪些好的解决方案可以深度克隆状态、对克隆进行更改,然后放弃更改或应用它们? 这里的示例非常基本,解决方案必须适用于更复杂的对象/树。

Edit 1:
有一个图书馆叫vuex 撤消重做 https://github.com/anthonygore/vuex-undo-redo,它基本上记录了突变,但有一些问题。在另一个 Stack Overflow 主题中在 Vue.js vuex 上返回类似 Undo Redo 的状态 https://stackoverflow.com/questions/42878329/going-back-to-states-like-undo-redo-on-vue-js-vuex推荐使用vuex函数replaceState(state).


您可以使用JSON.stringify and JSON.parse with replaceState.

In vuex:

const undoStates = [];

// save state
undoStates.push(JSON.stringify(state));

// call state (remove from stack)
if (undoStates.length > 0) {
  this.replaceState(JSON.parse(undoStates.pop()));
}

这将创建整个状态的副本,但您也可以使用商店的一部分:

const animalStates = [];

// save state
animalStates.push(JSON.stringify(state.animals));

// call state (remove from stack)
if (animalStates.length > 0) {
  let animals = JSON.parse(animalStates.pop());
  this.replaceState({...state, animals} );
}

这会将当前状态与您选择的对象合并(例如本例中的动物)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Vuex中深度克隆状态并回滚? 的相关文章

随机推荐