如何用vue删除重复列表?

时间:2018-01-23 14:26:22

标签: javascript vue.js vuejs2

当添加到购物车时,显然会重复,我认为不应该这样!当我点击+,然后浏览添加的购物车列表,这是重复的,我希望这是添加到购物车的列表应该是唯一的!转到jsfiddle

看看gif:

enter image description here

看图片:

enter image description here

的javascript:

const phone = [{
      id: "1",
      name: "Iphone 4S",
      price: 300,
      quantity: 0
    }, {
      id: "2",
      name: "Xiaomi",
      price: 200,
      quantity: 0
    }, {
      id: "3",
      name: "vivo X20",
      price: 320,
      quantity: 0
    }]
var app = new Vue({
  el: "#app",
  data: {
    phone:phone,
    addcart: [],
    showcart: false,
  },
  computed: {
    total() {
      var total = 0;
      for (var i = 0; i < this.addcart.length; i++) {
        total += this.addcart[i].price;
      }
      return total;
    }
  },
  methods: {
    lessClick(item) {
        if (item.quantity > 0) {
          item.quantity -= 1
          const index = this.addcart.indexOf(item)
          if (index > -1) {
            const removedName = this.addcart.splice(index, 1)
            console.log("remove:", removedName)
          }
        }
      },
      addClick(item) {
      this.showcart = false
        item.quantity += 1
        console.log("add:", this.addcart.push(item))

      },
       showCarts(){
       //this.showcart = true      
       }
  }
})

HTML:

<div id="app">
  <ul class="cart-ul">
    <li v-for="(item,index) in phone">
      Product name: {{item.name}}
      <br>Product price:{{item.price}}
      <br>
      <a class="a-less" @click="lessClick(item)">-</a>
      <input type="text" v-model="item.quantity">
      <a class="a-add" @click="addClick(item)">+</a>
    </li>
  </ul>
  <!--<button @click="showCarts">
     {{addcart.length}}
   </button>-->
  <div class="cart">
    <div>
      <ul>
        <li v-for="item in addcart">
          <p><strong>{{ item.quantity }}</strong> - {{ item.name }}</p>
        </li>
      </ul>
       <h5>Total: <span>{{ total }}</span></h5>
    </div>
  </div>

</div>

1 个答案:

答案 0 :(得分:1)

您可以先搜索项目是否在列表中,如果不是,只需添加项目,但如果项目在数组中,则只需增加数量:

addClick(item) {
      this.showcart = false;
      const indexItem = this.addcart.findIndex(x=>x.id === item.id);
      if(indexItem >= 0){
        this.addcart[indexItem].quantity += 1;
      }else{
        item.quantity += 1;
        this.addcart.push(item);
      }
},