Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

vue 购物车

image.png

 items: [{
                    title: "苹果",
                    price: 10,
                    count: 2,
                }, {
                    title: "芒果",
                    price: 10,
                    count: 2,
                }, {
                    title: "葡萄",
                    price: 10,
                    count: 2,
                }, ],

上面是后台数据 默认数量 后台count传入 用户可以点击加减 也可以 自定义输入数量 如何 双向绑定


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

加减使用@click绑定自定义事件,
中间input使用v-model双向绑定变量就可以了。
一段伪代码例子:

<template lang='pug>
  ul
    li(v-for='(item,index) in cartsList' :key='index')
      label {{ item.title }}
      span
        a(@click='add(index)') +
        input(v-model='cardList[index].count')
        a(@click='sub(index)') -
      span $ {{item.price}}
      span $ {{item.price*item.count}}
  p {{ total.count }}件商品, $ {{total.price}}
</tempalte>
<script>
export default {
  data(){
    return{
        cartsList:[],
    }
  },
  computed:{
    total(){
      let count = 0
      let price = 0
      this.cartsList.foreach(item=>{
        count+=item.count
        price+=item.count*item.price
      })
      return { count:count,price:price }
    }
  },
  methods:{
    add(index){
      this.cartsList[index].count +=1
    },
    sub(index){
      this.cartsList[index].count += -1
    }
    
  }
}
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...