101 / 112
Как реализовать undo/redo в Vue-приложении?
Храни массив предыдущих состояний (history stack) и указатель на текущую позицию. Undo перемещает указатель назад, redo -- вперёд. Каждое действие пользователя пушит новый снапшот.
JavaScript
const history = ref([structuredClone(initialState)])
const index = ref(0)
function push(state) {
history.value = history.value.slice(0, index.value + 1)
history.value.push(structuredClone(state))
index.value++
}
function undo() { if (index.value > 0) index.value-- }
function redo() { if (index.value < history.value.length - 1) index.value++ }
const current = computed(() => history.value[index.value])