【ES6系列】Proxy 数据保护实例

业务场景:对数据进行升序、降序、重置操作而不影响原始数据,除了用闭包的方式实现之外,还可以用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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值