Vue实现简易购物车功能

效果演示:

 代码展示:

<!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>
        *{
            margin: 0;
            padding: 0;
        }
        li{
            list-style: none;
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 500px;
            height: 100px;
        }
        ul li input{
            width: 15px;
            text-align: center;
        }
        ul li img{
            width: 80px;
            height: 80px;
        }
    </style>
</head>
<body>
    <div id="app">
        <!-- 全选框 -->
        <input type="checkbox" v-model="checkedAll" @change="checkboxAll">
        <ul>
            <!-- 循环遍历数组goods -->
            <li v-for="(item,index) in goods">
                <input type="checkbox" v-model="checkedOther" :value="item.id" @change="checkboxOther">
                <img :src="item.pic" alt="">
                <span>
                <p>商品名:{{item.name}}</p>
                <p>商品价格:{{item.price}}</p>
                </span>
                <!-- :disabled ="item.num === 1" 设置禁用属性 最小值 -->
                <button @click="subtract(item)" :disabled ="item.num === 1" >-</button>
                <input type="text" v-model="item.num">
                <!-- :disabled = "item.limit === item.num" 最大值 -->
                <button @click="add(item)" :disabled = "item.limit === item.num">+</button>
                <p>小计:{{subtotal(item)}}</p>
                <button @click="del(index)">删除</button>
            </li>
        </ul>
        <h2>总计:{{total}} </h2>
    </div>
    <script>
        new Vue({
            el:'#app',
            data:{
                checkedAll:false,
                total:0,
                checkedOther:[],
                goods:[
                {
                        "id":0,
                        "name":"商品1",
                        "price":10,
                        "num":1,
                        "limit":5,            
                        "pic":"https://static.maizuo.com/pc/v5/usr/movie/44dc08914d508fc47c8267c6ca73f2d8.jpg"
                    },
                    {
                        "id":1,
                        "name":"商品2",
                        "price":20,
                        "num":2,
                        "limit":5,
                        "pic":"https://static.maizuo.com/pc/v5/usr/movie/44dc08914d508fc47c8267c6ca73f2d8.jpg"
                    },
                    {
                        "id":2,
                        "name":"商品3",
                        "price":30,
                        "num":3,
                        "limit":5,
                        "pic":"https://static.maizuo.com/pc/v5/usr/movie/44dc08914d508fc47c8267c6ca73f2d8.jpg"
                    }
                ]
                
            },
            methods:{
                // 全选单选函数
                checkboxAll(){
                    console.log(this.checkedAll);
                    // 如果this.checkedAll为true 则循环遍历goods数组中的id属性写入 this.checkedOther
                    // 全选
                    if(this.checkedAll){
                        this.goods.forEach(element => {
                            this.checkedOther.push(element.id)
                        });
                    }else{
                        // 如果this.checkedAll为false,则赋值空数组
                        // 全不选
                        this.checkedOther = [];
                    }
                    // 单选全选改变,重新计算总价
                    this.getTotal();
                },
                // 单选函数
                checkboxOther(){
                    //  当this.checkedOther数组的长度等于this.goods数组的长度
                    //  则说明全部选中 
                    if(this.checkedOther.length === this.goods.length){
                        this.checkedAll = true;
                    }else{
                        // 否则就是未选中
                        this.checkedAll = false;
                    }
                    // 单选全选改变,重新计算总价
                    this.getTotal();

                },
                // 购买数量增加 
                add(item){
                    item.num++
                    // 一旦数值改变,重新计算总价
                    this.getTotal();
                },
                // 购买数量减少
                subtract(item){
                    item.num--
                    // 一旦数值改变,重新计算总价
                    this.getTotal();
                },
                // 计算总价函数
                getTotal() {
                    this.total = 0;
                    // 循环遍历数组中选中的商品
                    this.goods.forEach(item => {
                        // 查询this.checkedOther 中是否有id属性,有说明被选中
                        // 执行this.total的加等操作
                        if (this.checkedOther.indexOf(item.id) != -1) {
                            this.total += item.price * item.num;
                        }
                    })
                },
                // 删除
                del(index){
                    if(confirm('确定删除这个商品吗?'))
                    this.goods.splice(index,1)
                }

            },
            // computed计算属性
            computed: {
                // 小计 这里可以用函数的形式去写
                // 但博主想联系一下计算属性传参
                // 因此用计算属性去写
                subtotal(){
                    return function(item){
                        return item.price*item.num 
                    }
                },
            }
        })
    </script>
</body>
</html>
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是一个简单购物车应用程序,使用Vue.js和Node.js进行构建: 前端: 1. 创建Vue.js项目:可以使用Vue CLI进行创建,输入以下命令: ``` vue create shopping-cart ``` 2. 安装必要的依赖项: ``` npm install axios vue-router vuex bootstrap-vue ``` 3. 创建组件: - App.vue:主组件,包含路由和导航栏 - Home.vue:主页组件,用于显示产品列表,并允许用户将产品添加到购物车 - Cart.vue购物车组件,用于显示已添加到购物车的产品,并允许用户更改数量或删除产品 4. 创建路由: 在main.js文件中,使用以下代码创建路由: ```javascript import VueRouter from 'vue-router' import Home from './components/Home.vue' import Cart from './components/Cart.vue' const routes = [ { path: '/', component: Home }, { path: '/cart', component: Cart } ] const router = new VueRouter({ routes }) new Vue({ router, render: h => h(App), }).$mount('#app') ``` 5. 创建Vuex store: 在store.js文件中,使用以下代码创建store: ```javascript import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { cart: [] }, mutations: { addToCart(state, product) { const item = state.cart.find(item => item.id === product.id) if (item) { item.quantity++ } else { state.cart.push({...product, quantity: 1}) } }, removeFromCart(state, product) { const index = state.cart.findIndex(item => item.id === product.id) state.cart.splice(index, 1) }, updateQuantity(state, {product, quantity}) { const item = state.cart.find(item => item.id === product.id) item.quantity = quantity } }, actions: { addToCart({commit}, product) { commit('addToCart', product) }, removeFromCart({commit}, product) { commit('removeFromCart', product) }, updateQuantity({commit}, {product, quantity}) { commit('updateQuantity', {product, quantity}) } }, getters: { cartTotal(state) { return state.cart.reduce((total, item) => total + item.price * item.quantity, 0) }, cartItemCount(state) { return state.cart.reduce((total, item) => total + item.quantity, 0) } } }) ``` 6. 创建API服务: 使用Node.js和Express创建一个简单的API,用于获取产品列表: ```javascript const express = require('express') const app = express() const products = [ { id: 1, name: 'Product 1', price: 10 }, { id: 2, name: 'Product 2', price: 20 }, { id: 3, name: 'Product 3', price: 30 }, { id: 4, name: 'Product 4', price: 40 } ] app.get('/api/products', (req, res) => { res.json(products) }) app.listen(3000, () => { console.log('Server listening on port 3000') }) ``` 7. 使用Axios获取数据: 在Home.vue组件中,使用Axios获取产品列表,并将其显示在页面上: ```javascript <template> <div class="container"> <div class="row"> <div class="col-sm-4" v-for="product in products" :key="product.id"> <div class="card"> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.price }}</p> <button class="btn btn-primary" @click="addToCart(product)">Add to Cart</button> </div> </div> </div> </div> </div> </template> <script> import axios from 'axios' import { mapActions } from 'vuex' export default { name: 'Home', methods: { ...mapActions(['addToCart']), async getProducts() { const response = await axios.get('/api/products') this.products = response.data } }, data() { return { products: [] } }, mounted() { this.getProducts() } } </script> ``` 8. 在Cart.vue组件中显示购物车: 在Cart.vue组件中,使用Vuex store中的数据显示已添加到购物车的产品,并允许用户更改数量或删除产品: ```javascript <template> <div class="container"> <div class="row"> <div class="col-sm-8"> <div class="card mb-3" v-for="item in cart" :key="item.id"> <div class="card-body"> <h5 class="card-title">{{ item.name }}</h5> <p class="card-text">{{ item.price * item.quantity }}</p> <div class="input-group mb-3"> <div class="input-group-prepend"> <button class="btn btn-outline-secondary" type="button" @click="decrementQuantity(item)">-</button> </div> <input type="text" class="form-control" :value="item.quantity" @input="updateQuantity(item, $event.target.value)"> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="button" @click="incrementQuantity(item)">+</button> </div> </div> <button class="btn btn-danger" @click="removeFromCart(item)">Remove</button> </div> </div> </div> <div class="col-sm-4"> <div class="card"> <div class="card-body"> <h5 class="card-title">Cart Summary</h5> <p class="card-text">Total items: {{ cartItemCount }}</p> <p class="card-text">Total price: {{ cartTotal }}</p> <router-link to="/" class="btn btn-primary">Continue Shopping</router-link> </div> </div> </div> </div> </div> </template> <script> import { mapState, mapActions } from 'vuex' export default { name: 'Cart', computed: { ...mapState(['cartTotal', 'cartItemCount']), cart() { return this.$store.state.cart } }, methods: { ...mapActions(['removeFromCart', 'updateQuantity']), incrementQuantity(product) { this.updateQuantity({product, quantity: product.quantity + 1}) }, decrementQuantity(product) { if (product.quantity > 1) { this.updateQuantity({product, quantity: product.quantity - 1}) } } } } </script> ``` 后端: 1. 创建Node.js项目: 在命令行中,输入以下命令创建一个新的Node.js项目: ``` mkdir shopping-cart-backend cd shopping-cart-backend npm init -y ``` 2. 安装必要的依赖项: ``` npm install express cors ``` 3. 创建API服务: 在index.js文件中,使用以下代码创建API服务: ```javascript const express = require('express') const cors = require('cors') const app = express() app.use(cors()) const products = [ { id: 1, name: 'Product 1', price: 10 }, { id: 2, name: 'Product 2', price: 20 }, { id: 3, name: 'Product 3', price: 30 }, { id: 4, name: 'Product 4', price: 40 } ] app.get('/api/products', (req, res) => { res.json(products) }) app.listen(3000, () => { console.log('Server listening on port 3000') }) ``` 4. 启动API服务: 在命令行中,输入以下命令启动API服务: ``` node index.js ``` 现在,您可以在浏览器中访问http://localhost:3000/api/products,以获取产品列表。 完成以上步骤后,您可以使用以下命令启动Vue.js应用程序: ``` npm run serve ``` 然后,您可以在浏览器中访问http://localhost:8080,以查看并测试购物车应用程序。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大聪明码农徐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值