vue2组件实现购物车功能(可直接使用)

简介: vue2组件实现购物车功能(可直接使用)

此篇文章的代码实现了没有数据库的情况下如何保存数据在本机,在有数据的情况下关闭浏览器,再次打开数据依然存在,第一次打开时会报错,因为无法从本机浏览器找到数据,下面我们展示代码

<body>
    <div id="app">
        <div>
            <form action="">
                商品名称 :<input type="text" v-model="productName" name="productName">
                商品单价 :<input type="text" v-model="productPrice" name="productPrice">
                <input type="button" @click="addProduct" value="添加商品">
            </form>
        </div>
        <ul>
            <li v-for="(pro,index) in productList" :key="index">
                商品名称:{{pro.productName}} --------- 商品单价:{{pro.productPrice}}
                <button type="button" @click="addProtoCart(index)">添加购物车</button>
                <button type="button" @click="deleteProToCart(index)">删除此商品</button>
            </li>
        </ul>
        <cart :cartlist="cartList"></cart>
    </div>
    <template id="cartHtml">
        <div>
            <table border="1">
                <tr>
                    <td><input type="checkbox" id="quanxuan" @click="quanxua"></td>
                    <td>商品名称</td>
                    <td>商品单价</td>
                    <td>商品数量</td>
                    <td>价格</td>
                </tr>
                <tr v-for="(pro,index) in cartlist" :key="index">
                    <td><input type="checkbox" v-model="pro.active" @change="xuan"></td>
                    <td>{{pro.productName}}</td>
                    <td>{{pro.productPrice}}</td>
                    <td>
                        <button @click="redProNum(index)">-</button>
                        {{pro.puoductNum}}
                        <button @click="addProNum(index)">+</button>
                    </td>
                    <td>{{pro.productPrice * pro.puoductNum}}</td>
                </tr>
                <tr>
                    <td colspan="3">选中的数量:{{activeNum}}/{{cartlist.length}}</td>
                    <td colspan="2">总价格:{{totalPrice}}</td>
                </tr>
            </table>
        </div>
    </template>
</body>
<script src="../js/vue2.7.js"></script>
<script>
    var cart={
        template:"#cartHtml",
        props:['cartlist'],
        methods:{
            addProNum(index){
                let product=this.cartlist[index]
                product.puoductNum++
                localStorage.removeItem("cartList");
                localStorage.setItem('cartList', JSON.stringify(this.cartlist));
            },
            redProNum(index){
                let product=this.cartlist[index]
                //判断商品数量是否为一
                if (product.puoductNum==1) {
                    this.cartlist.splice(index,1)//为1,从数组中删除
                    localStorage.removeItem("cartList");
                    localStorage.setItem('cartList', JSON.stringify(this.cartlist));
                }else{
                    product.puoductNum--
                    localStorage.removeItem("cartList");
                    localStorage.setItem('cartList', JSON.stringify(this.cartlist));
                }
            },
            quanxua(){
                if(document.getElementById("quanxuan").checked){
                    for(var i=0;i<this.cartlist.length;i++){
                        this.cartlist[i].active=true;
                    }
                    localStorage.removeItem("cartList");
                    localStorage.setItem('cartList', JSON.stringify(this.cartlist));
                    console.log(localStorage.getItem("cartList"));
                }else{
                    for(var i=0;i<this.cartlist.length;i++){
                        this.cartlist[i].active=false;
                    }
                    localStorage.removeItem("cartList");
                    localStorage.setItem('cartList', JSON.stringify(this.cartlist));
                }
            },
            xuan(){
                localStorage.removeItem("cartList");//删除浏览器的本地存储
                localStorage.setItem('cartList', JSON.stringify(this.cartlist));//添加到浏览器的本地存储
            }
        },
        computed:{
            //选中了几个商品
            activeNum(){
                let num=0;
                let activeProductList=this.cartlist.filter(item=>{
                    return item.active
                })
                return activeProductList.length;
            },
            //计算总价
            totalPrice(){
                let result=0
                for (pro of this.cartlist) {
                    if (pro.active) {
                        result=result+pro.productPrice*pro.puoductNum
                    }
                }
                return result
            },
        },
        //修改的时候进行判断复选框是否全选
        updated() {
            var isActive=this.cartlist.every(c => c.active)
            if (isActive) {
                document.getElementById("quanxuan").checked=true
            } else {
                document.getElementById("quanxuan").checked=false
            }
        },
    }
    var app1=new Vue({
        el:"#app",
        data(){
            return{
                productName:"",
                productPrice:"",
                productList:[
                ],
                cartList:[
                ]
            }
        },
        methods:{
            //添加商品
            addProduct(){
                let isnameOk=true;
                let ispriceOk=true;;
                //对新增的商品名称和单价进行验证
                if (this.productName==null||this.productName=="") {
                    isnameOk=false
                }
                if(isNaN(this.productPrice) || this.productPrice<=0){
                    ispriceOk=false;
                }
                if (isnameOk&&ispriceOk) {
                    //查找新增的商品是否存在一商品列表中,如果不存在返回-1
                    let findindex=this.productList.findIndex(item=>{
                        return item.productName==this.productName
                    })
                    if (findindex==-1) {//判断商品列表是否存在新增的商品
                        //把新商品添加导商品列表中
                        this.productList.push({productName:this.productName,productPrice:this.productPrice})
                        localStorage.removeItem("productList");//删除本地浏览器存储
                        localStorage.setItem('productList', JSON.stringify(this.productList));//储存到本地浏览器
                    }else{
                        alert("此商品已经存在商品列表中")//商品已存在,给出提示
                    }
                }else{
                    alert("请输入合适的商品名称及单价")
                }
            },
            //添加商品到购物车,index是点击商品的下标
            addProtoCart(index){
                let newproduct=this.productList[index]//根据下标从商品列表中取出商品对象
                //从购物车列表中查找,是否存在新的商品,如果找到返回购物车中的商品
                let product =this.cartList.find(item=>{
                    return item.productName==newproduct.productName
                })
                if (product) {
                    //如果有对应的商品则数量加一
                    product.puoductNum++
                }else{
                    //没有对应的商品就添加商品到购物车
                    this.cartList.push({
                        productName:newproduct.productName
                        ,productPrice:newproduct.productPrice
                        ,puoductNum:1
                        ,active:true
                    })
                    localStorage.removeItem("cartList");
                    localStorage.setItem('cartList', JSON.stringify(this.cartList));
                }
            },
            //删除商品
            deleteProToCart(index){
                alert("删除商品")
                this.productList.splice(index,1)
                localStorage.removeItem("productList");
                localStorage.setItem('productList', JSON.stringify(this.productList));
            }
        },
        //打开浏览器加载保存的数据
        mounted(){
            for(pro of JSON.parse(localStorage.getItem("productList"))){
                this.productList.push({productName:pro.productName,productPrice:pro.productPrice});
            }
            for(pro of JSON.parse(localStorage.getItem("cartList"))){
                this.cartList.push({productName:pro.productName,productPrice:pro.productPrice,puoductNum:pro.puoductNum,active:pro.active});
            }
        },
        //组件
        components:{
            cart
        },
    })
</script>
相关文章
|
16天前
|
JavaScript 前端开发 安全
【vue】如何修改iview组件的样式(element同)
【vue】如何修改iview组件的样式(element同)
21 1
|
16天前
|
JavaScript UED
【vue】iview组件 DatePicker 日期选择器如何显示默认当前日期
【vue】iview组件 DatePicker 日期选择器如何显示默认当前日期
25 1
|
2天前
|
编译器
vue3组件TS类型声明实例代码
vue3组件TS类型声明实例代码
4 0
|
2天前
|
JavaScript 前端开发 IDE
vue3基础: 组件注册
vue3基础: 组件注册
10 0
|
2天前
|
JavaScript
vue3使用element-plus 树组件(el-tree)数据回显
vue3使用element-plus 树组件(el-tree)数据回显
5 0
|
3天前
|
缓存 JavaScript
在 Vue 组件中使用计算属性和侦听器来响应路由变化
Vue Router 中,计算属性和侦听器常用于根据路由变化更新组件状态。计算属性缓存依赖,当路由参数改变时自动更新,如示例中的 `userId`。侦听器则监听 `$route` 变化,执行相应操作,例如在 `currentUserId` 示例中响应 `userId` 更新。计算属性适合简单变化,而异步操作或复杂场景可选用侦听器。Vue 3 中,`watchEffect` 减少了部分侦听场景的复杂性。总之,它们用于组件内部响应路由变化,而非直接处理路由逻辑。
11 4
|
4天前
|
JavaScript
Vue3的 组件事件
Vue3的 组件事件
16 0
|
4天前
|
存储 JavaScript
vue3组件之间传值通讯
vue3组件之间传值通讯
8 0
|
4天前
|
资源调度 JavaScript 前端开发
vue3怎么调用vant中的icon组件
vue3怎么调用vant中的icon组件
17 4
|
4天前
|
JavaScript
vue实现递归组件
vue实现递归组件
12 0