共计 2192 个字符,预计需要花费 6 分钟才能阅读完成。
<template>
<div class="box">
<div class="header">
<button @click="handleHistoryBack"> 撤销 </button>
<button @click="handleHistoryAhead"> 后退 </button>
<button @click="handleRecover"> 还原 </button>
</div>
<div class="main">
<button
v-for="(item, index) in list"
:key="item.id"
:class="{active: index === listIndex}"
@click="handItem(item, index)"
>
{{item}}
</button>
</div>
<div>
<p>historyIndex:{{historyIndex}}</p>
<p>curHistoryIndex:{{curHistoryIndex}}</p>
<p>backStep:{{backStep}}</p>
<p>--------</p>
<p>historyIndexList:{{historyIndexList}}</p>
<p>historyActiveList:{{historyActiveList}}</p>
</div>
</div>
</template>
<script>
export default {data () {
return {list: ['a', 'b', 'c', 'd', 'e'],
listIndex: 0,
listActive: {},
historyIndexList: [],
historyActiveList: [],
historyIndex: 0,
curHistoryIndex: 0,
backStep: 0
}
},
created () {this.initData()
},
methods: {initData () {
this.listIndex = 0
this.listActive = this.list[this.listIndex]
this.setHistory()},
handItem (item, index) {if (this.listIndex === index) {return false}
this.listActive = item
this.listIndex = index
this.setHistory()},
setHistory () {if (this.backStep > 0) {
const spliceIndex = this.historyIndexList.length - this.backStep
this.historyIndexList.splice(spliceIndex)
this.historyActiveList.splice(spliceIndex)
this.backStep = 0
this.historyIndex = this.curHistoryIndex
}
this.historyIndexList.push(this.listIndex)
this.historyActiveList.push(this.listActive)
this.historyIndex++
this.curHistoryIndex++
},
setData () {this.listIndex = this.historyIndexList[this.curHistoryIndex - 1]
this.listActive = this.historyActiveList[this.curHistoryIndex - 1]
},
handleHistoryBack () {if (this.curHistoryIndex <= 1) {
this.curHistoryIndex = 1
alert('不能再后退')
return false
} else {this.curHistoryIndex--}
if (this.backStep >= this.historyIndex) {this.backStep = this.historyIndex} else {this.backStep++}
this.setData()},
handleHistoryAhead () {if (this.curHistoryIndex >= this.historyIndex) {
this.curHistoryIndex = this.historyIndex
alert('不能再后退')
return false
} else {this.curHistoryIndex++}
if (this.backStep <= 0) {this.backStep = 0} else {this.backStep--}
this.setData()},
handleRecover () {
this.backStep = 0
this.historyIndexList = []
this.historyActiveList = []
this.historyIndex = 0
this.curHistoryIndex = 0
this.initData()}
}
}
</script>
<style scoped lang="less">
button {
width: 100px;
height: 40px;
cursor: pointer;
&.active {color: red;}
}
</style>
正文完