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>

猜你喜欢

转载自blog.csdn.net/m0_65491952/article/details/132291949