javascript - vue如何去除重复列表?

标签 javascript vue.js vuejs2

加入购物车的时候,明明是重复的,我觉得不应该!当我点击+,然后遍历添加购物车的列表,这是重复的,我希望这是添加到购物车的列表应该是唯一的!转到 jsfiddle .

看动图:

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>

最佳答案

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

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);
      }
},

关于javascript - vue如何去除重复列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48404072/

相关文章:

javascript - 带有额外 li 的 Vue.js v-for 不呈现

javascript - VueJS 和 Laravel mix 中渲染错误

vue.js - [Vue警告] : (deprecation ATTR_FALSE_VALUE)

nginx - Axios 中的 Cors OPTIONS 方法在 Laravel 和 Nginx 中失败

javascript - 建议 : Single Page application architecture issue

javascript - 页面重定向在 Firefox 中无法使用 window.location 工作,但在 chrome 中工作

javascript - 将原型(prototype)函数存储在变量中

javascript - 在 UIwebview 中查找单词

javascript - 带有 ChartJS 的 Vuejs 从 API 填充

javascript - 如果 XML 是外部的,为什么 Javascript 不能处理 XML