Vue中实现高低排序

下面是例子

  <button @click="up">从高到低</button>
  <button @click="down">从低到高</button>

js代码

export default {
  data() {
    return {
      itemList: [1, 2, 3, 4, 5, 6]
    };
  },
  methods: {
    // 从高到低
    up() {
    	this.itemList.sort((a, b) => {
            return a - b;
         });   
      //这个是另一种写法
      //function fn(a, b) {
      // return -(a - b);
      //}
      //this.a = this.a.sort(fn);
    },
    // 从低到高
    down(){
		this.itemList.sort((a, b) => {
            return b - a;
         }); 
	  //这个是另一种写法	
      //function fn(a, b) {
      //return (a - b);
      //}
      //this.a = this.a.sort(fn);
    }
  }
};
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,针对你的问题,我可以给你提供一些指导。 1. 商品价格升降排序: 如果你使用的是 Vue 2.x,你可以使用 `v-for` 指令来循环渲染商品列表,并且在 `v-for` 指令使用 `v-bind` 指令来绑定商品价格。例如: ``` <div v-for="product in products" :key="product.id"> <p>{{ product.name }}</p> <p>价格:{{ product.price }}</p> </div> ``` 如果你想要实现价格排序,你可以在 Vue 组件的 `methods` 选项定义一个排序的方法,并在模板使用 `v-on:click` 指令来绑定这个方法。例如: ``` <template> <div> <button @click="sortAscending">价格从到高</button> <button @click="sortDescending">价格从高到</button> <div v-for="product in sortedProducts" :key="product.id"> <p>{{ product.name }}</p> <p>价格:{{ product.price }}</p> </div> </div> </template> <script> export default { data() { return { products: [ { id: 1, name: '商品 A', price: 100 }, { id: 2, name: '商品 B', price: 200 }, { id: 3, name: '商品 C', price: 300 } ] } }, methods: { sortAscending() { this.products.sort((a, b) => a.price - b.price) }, sortDescending() { this.products.sort((a, b) => b.price - a.price) } }, computed: { sortedProducts() { return this.products.slice() } } } </script> ``` 在这个例子,我们定义了两个排序方法 `sortAscending` 和 `sortDescending`,分别对应价格从到高和价格从高到排序。我们还定义了一个计算属性 `sortedProducts`,用来返回已经排序的商品列表。在模板,我们使用 `v-for` 指令来循环渲染 `sortedProducts`,并绑定每个商品的 `id` 作为 `key`。 2. 商品删除: 如果你想要实现商品删除,你可以在模板使用 `v-on:click` 指令来绑定一个删除方法。例如: ``` <template> <div> <div v-for="product in products" :key="product.id"> <p>{{ product.name }}</p> <p>价格:{{ product.price }}</p> <button @click="removeProduct(product)">删除</button> </div> </div> </template> <script> export default { data() { return { products: [ { id: 1, name: '商品 A', price: 100 }, { id: 2, name: '商品 B', price: 200 }, { id: 3, name: '商品 C', price: 300 } ] } }, methods: { removeProduct(product) { const index = this.products.indexOf(product) this.products.splice(index, 1) } } } </script> ``` 在这个例子,我们在模板为每个商品渲染一个“删除”按钮,并绑定一个 `removeProduct` 方法来处理删除操作。在这个方法,我们使用 `Array.prototype.indexOf()` 函数来找到要删除的商品在商品列表索引,然后使用 `Array.prototype.splice()` 函数来从商品列表删除这个商品。 希望以上内容能够对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值