programing

Vue.js vuex에서의 실행 취소와 같은 상태로 되돌아가다

itsource 2022. 7. 3. 23:34
반응형

Vue.js vuex에서의 실행 취소와 같은 상태로 되돌아가다

Vuex를 사용하여 실행 취소/재실행하는 방법저는 매우 복잡한 앱을 만들고 있는데, Vue dev 툴이 상태 전환에 많은 도움이 되었기 때문에 앱에 그 기능을 탑재하고 싶습니다.어떻게 하면 좋을까요?

undo-redo를 다음과 같이 구현했습니다.

1) vuex용 플러그인 생성

const undoRedoPlugin = (store) => {
  // initialize and save the starting stage
  undoRedoHistory.init(store);
  let firstState = cloneDeep(store.state);
  undoRedoHistory.addState(firstState);

  store.subscribe((mutation, state) => {
    // is called AFTER every mutation
    undoRedoHistory.addState(cloneDeep(state));
  });
}

2) 플러그인 사용

new Vuex.Store({
... 
  plugins: [undoRedoPlugin]
});

3) 상태 이력을 undoRedoHistory에 저장합니다.

class UndoRedoHistory {
  store;
  history = [];
  currentIndex = -1;

  init(store) {
    this.store = store;
  }

  addState(state) {
    // may be we have to remove redo steps
    if (this.currentIndex + 1 < this.history.length) {
      this.history.splice(this.currentIndex + 1);
    }
    this.history.push(state);
    this.currentIndex++;
  }

  undo() {
    const prevState = this.history[this.currentIndex - 1];
    // take a copy of the history state
    // because it would be changed during store mutations
    // what would corrupt the undo-redo-history
    // (same on redo)
    this.store.replaceState(cloneDeep(prevState));
    this.currentIndex--;
  }

  redo() {
    const nextState = this.history[this.currentIndex + 1];
    this.store.replaceState(cloneDeep(nextState));
    this.currentIndex++;
  }
}

const undoRedoHistory = new UndoRedoHistory();

4) 사용

undoRedoHistory.undo();
...
undoRedoHistory.redo();

클론 복제보다 큰 규모의 상태가 아니라면 이 상태가 좋은 방법입니다.

참조: https://vuex.vuejs.org/en/api.html

쉽게 사용할 수 있다subscribe(handler: Function)지정된 Store에서 원하는 모든 상태를 배열로 유지하는 함수를 등록합니다.

그런 다음 해당 어레이에 저장된 상태를 인수로 지정하여replaceState(state: Object).

언급URL : https://stackoverflow.com/questions/42878329/going-back-to-states-like-undo-redo-on-vue-js-vuex

반응형