2017-03-18 5 views

Antwort

4

Ich habe implementiert Undo-Redo wie folgt:

1) für 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) ein Plugin erstellen verwenden das Plugin

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

3) speichern eine Geschichte von die Zustände in 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) verwenden Sie es

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

Wenn Ihr Zustand in der Größe als das Klonen nicht sehr groß ist, dass ein guter Ansatz besagt ist.

5

See: https://vuex.vuejs.org/en/api.html

Sie verwenden subscribe(handler: Function) easely können eine Funktion zu registrieren, die alle Staaten halten Sie von einem bestimmten Shop wollen in einem Array.

Dann können Sie einen beliebigen gespeicherten Status in diesem Array verwenden, indem Sie sie als Argument an replaceState(state: Object) übergeben.

Verwandte Themen