vue2 实现简易购物车

watch
默认监听

watch监听默认的是,值类型监听,只会监听数据值的变化,
当引用类型里面的任何一个值发生变化的时候,那么不会触发监听事件

// 侦听器
   watch: {
     // 监听number属性
    // 值类型属性监听
    // number: function (newValue,oldValue){
  /* 
  			形参: newValue
   			是数据改变后的值,
   		    形参:  oldValue
            是数据改变前的值
  */
  // console.log('number数据发生了变化');
 //  console.log(newValue,oldValue);
   //  }
   "obj.number": function (newValue,oldValue){
     console.log(newValue,oldValue);
          }
   }
深度监听 handler

handler 当数据发生变化的时候,触发此函数
// 虽然开启了深度监听,能够监听到对象里面的值得变化
// 但是没有办法知道具体是哪一个值发生了变化

//obj监听对象
obj: {
       handler: function (newValue){
       console.log(newValue);
  // handler 当数据发生变化的时候,触发此函数
  // console.log(123);
  // 虽然开启了深度监听,能够监听到对象里面的值得变化
  // 但是没有办法知道具体是哪一个值发生了变化
        },
  // 开启深度监听 默认为false
     deep: true
    }
computed计算

当需求的处理程度,过于复杂时,计算属性无非是我们更好的选择
计算属性 会随着data数据的更新来更新计算属性的值
获取data的数据 仍然以this开头

 computed: {
  // total: function 
  // 当计算属性内写getter或者setter时 具体用法是
  /* 
      属性: {
             // getter
               get: function (){
             // 这里是页面最终显示的数据  所有的数据处理在这里执行
           // 执行完成之后 仍然需要返回出去
                 return ‘值’
                        },
           // setter
           set: funciton (value){
     // 在计算属性进行修改的时候,会先触发setter属性,
     // 可以在这里进行数据的筛选等操作
       // set没有返回值
      // value就是操作的时候 赋予的值
                        }
                    }
 */
  total: {
    get: function (){
   var count = 0;
   this.list.forEach(item => {count += item})
                        return count
                    },
        set: function (value){
     for (const key in value) {
    value[key] = Number(value[key])
                        }
                        this.list = value;
                    }
                }

效果图
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
    <style>
        input{
            width: 50px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="app">
        <table border="1" rules="all">
            <thead>
                <tr>
                    <th><input type="checkbox" v-model="ckAll" @click="ckA()">全选</th>
                    <th>id 书名</th>
                    <th>日期</th>
                    <th>价格</th>
                    <th>数量</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item,index) in list" :key="item.id">
                    <!-- item.checked 绑定list数据的checked值 -->
                    <th><input type="checkbox" v-model="item.checked"></th>
                    <th> &nbsp; {{item.id}}-{{item.name}} &nbsp; </th>
                    <th> &nbsp; {{item.time}} &nbsp;</th>
                    <th> &nbsp; {{item.price}} &nbsp; </th>
                    <th> 
                        &nbsp; 
                        <!--数量为1 的时候禁用按钮 -->
                        <button @click="item.num==1?!ckAll:!item.num--" >-</button>
                        <input type="text" v-model="item.num">
                        <button @click="item.num++">+</button> 
                        &nbsp; 
                    </th>
                    <th><button @click="del(item.id)">删除</button></th>
                </tr>
            </tbody>
        </table>
        <h1>总金额:{{total.toFixed(2)}}</h1>
    </div>
</body>
<script>
    new Vue({
        el:"#app",
        data() {
            return {
                // 总开关全选 绑定的值
                ckAll:false,
                list:[
                    {
                        id:1,
                        name:"小红书",
                        time:"2023/2/11",
                        price:100,
                        num:2,
                        checked:false
                    },
                    {
                        id:2,
                        name:"小蓝书",
                        time:"2023/2/11",
                        price:100,
                        num:2,
                        checked:false
                    },
                    {
                        id:3,
                        name:"小绿书",
                        time:"2023/2/11",
                        price:100,
                        num:2,
                        checked:false
                    },
                    {
                        id:4,
                        name:"小白书",
                        time:"2023/2/11",
                        price:100,
                        num:2,
                        checked:false
                    },
                    {
                        id:5,
                        name:"小黄书",
                        time:"2023/2/11",
                        price:666,
                        num:2,
                        checked:false
                    }
                ]
            }
        },
        methods: {
            del(id){
                if(confirm("您确定delete我吗?")){
                    // filter 过滤id
                    // item.id!=id 返回新的list数据的条件
                    // 点击的id 不等于数组里的id 就完成了删除
                    this.list=this.list.filter(item=> item.id!=id)
                }
            },
            // 总开关全选控制 下面的每一个商品选项
            ckA() {
                this.list.forEach(item => item.checked = !this.ckAll);
            }
        },
        computed:{
            // 总金额 
            // reduce 累计相加
            total(){
                return this.list.reduce((sum,item)=>{
                    if(item.checked){
                        return sum+=Number(item.price)*Number(item.num)
                    }
                    return sum
                },0)
            }
        },
        watch: {
            // 商品反全选
            list: {
                handler: function () {
                    // every 遍历的每个item 其中一个为false 则返回false
                    this.ckAll = this.list.every((item) => {
                        return item.checked
                    })
                },
                deep: true
            }
        }
    })
</script>
</html>
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个基于 Vue 2 实现简单购物车的示例代码: HTML: ``` <div id="app"> <h2>商品列表</h2> <ul> <li v-for="item in goods" :key="item.id"> {{ item.name }} - {{ item.price }}元 <button @click="addToCart(item)">加入购物车</button> </li> </ul> <h2>购物车</h2> <table> <thead> <tr> <th>名称</th> <th>单价</th> <th>数量</th> <th>小计</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="(item, index) in cart" :key="item.id"> <td>{{ item.name }}</td> <td>{{ item.price }}元</td> <td> <button @click="minusFromCart(index)" :disabled="item.quantity === 1">-</button> {{ item.quantity }} <button @click="addToCart(item)">+</button> </td> <td>{{ item.price * item.quantity }}元</td> <td> <button @click="removeFromCart(index)">删除</button> </td> </tr> </tbody> </table> <p>总价:{{ totalPrice }}元</p> </div> ``` JavaScript: ``` new Vue({ el: '#app', data: { goods: [ { id: 1, name: '商品1', price: 10 }, { id: 2, name: '商品2', price: 20 }, { id: 3, name: '商品3', price: 30 } ], cart: [] }, methods: { addToCart(item) { let index = this.cart.findIndex(cartItem => cartItem.id === item.id) if (index !== -1) { this.cart[index].quantity++ } else { this.cart.push({ id: item.id, name: item.name, price: item.price, quantity: 1 }) } }, minusFromCart(index) { if (this.cart[index].quantity > 1) { this.cart[index].quantity-- } }, removeFromCart(index) { this.cart.splice(index, 1) } }, computed: { totalPrice() { return this.cart.reduce((total, item) => total + item.price * item.quantity, 0) } } }) ``` 在这个示例中,首先定义了一个商品列表和一个购物车列表,其中商品列表包含了每个商品的名称、价格和 ID,购物车列表为空。在页面上展示商品列表时,为每个商品添加了一个加入购物车的按钮,并在点击按钮时调用 `addToCart` 方法将对应商品信息加入购物车列表中。在页面上展示购物车列表时,使用了一个表格来展示每个商品的名称、价格、数量和小计金额,并为每个商品添加了加减和删除按钮,同时使用了一个计算属性来计算购物车中所有商品的总价。在 `addToCart` 方法中还实现了判断购物车中是否已存在该商品的逻辑,如果存在则将对应商品的数量加 1,否则将该商品添加到购物车列表中。在 `minusFromCart` 方法中实现了减少购物车中商品数量的逻辑,并且如果商品数量已经为 1,则减少按钮会被禁用。在 `removeFromCart` 方法中通过 `splice` 方法实现了删除购物车列表中的商品的逻辑。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值