业务场景:对数据进行升序、降序、重置操作而不影响原始数据,除了用闭包的方式实现之外,还可以用proxy来实现。
<template>
<div class="price">
<ul>
<li v-for="item in price"
:key="item">{{item}}</li>
</ul>
<button type="button"
@click="up">升序</button>
<button type="button"
@click="down">降序</button>
<button type="button"
@click="reset">重置</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data () {
return {
price: []
}
},
methods: {
up () {
this.price = this.proxy.up
},
down () {
this.price = this.proxy.down
},
reset () {
this.price = this.proxy.default
}
},
async mounted () {
let { data: { price } } = await axios.get('/proxy')
Object.freeze(price)
this.proxy = new Proxy({}, {
get (target, key) {
if (key === 'up') {
return [].concat(price).sort((a, b) => a - b)
} else if (key === 'down') {
return [].concat(price).sort((a, b) => b - a)
} else {
return price
}
},
set () {
return false
}
})
this.price = this.proxy.default
}
}
</script>
<style scoped>
ul,
li {
list-style: none;
}
</style>