vue实现购物车功能

简介: vue实现购物车功能

vue实现购物车功能

原理分析和实现

注意想实现该功能,需要学习:Vue学习之路(基础篇),深入的了解每个指令的使用

首先,还是先把布局写好,和引入vue,准备vue实例,这个不多说,代码如下


<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>vue实现购物车</title>
</head>
<body>
<div id="app">
    <h3>购物车</h3>
    名称:<input style="width:60px" type="text" v-model="nameValue"> <br/>
    单价:<input style="width:60px" type="text" v-model="priceValue"> <br/>
    数量:<input style="width:60px" type="text" v-model="countValue">
    <button @click="add()">添加购物车</button>
    <hr/>
    <table border="1">
        <tr>
            <td>名称</td>
            <td>单价</td>
            <td>数量</td>
            <td>小计</td>
        </tr>
        <tr v-for="(product,index) in products">
            <td>{{product.name}}</td>
            <td>{{product.price}}</td>
            <td>
                <button @click="desc(index)">-</button>
                {{product.count}}
                <button @click="incr(index)">+</button>
            </td>
            <td>{{product.price*product.count}}</td>
        </tr>
        <tr>
            <td colspan="4">总价:{{total()}}元</td>
        </tr>
    </table>
</div>
</body>
</html>
<script src="js/vue-min.js"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            products: [
                {name: "秋裤", price: "81", count: 2},
                {name: "华为", price: "5810", count: 1},
            ],
            nameValue: "",
            priceValue: "",
            countValue: 0,
            totalPrice:0
        },
        methods: {
            incr(index) {
                this.products[index].count++;
            },
            desc(index) {
                this.products[index].count--;
            },
            add() {
                this.products.push({name: this.nameValue, price: this.priceValue, count: this.countValue});
                this.nameValue = "";
                this.priceValue = "";
                this.countValue = 0;
            },
            total(){
                var price=0;
                for (var i = 0; i <this.products.length; i++) {
                    price+=this.products[i].price * this.products[i].count
                }
                return price.toFixed(2);
            }
        }
    })
</script>


image.png

相关文章
|
29天前
|
JavaScript
|
1月前
|
资源调度
Vue3导入表格功能
Vue3导入表格功能
|
1月前
|
JavaScript 前端开发
vue制作拍照、录像功能
vue制作拍照、录像功能
|
2月前
|
监控
【Vue3】学习watch监视:深入了解Vue3响应式系统的核心功能(下)
【Vue3】学习watch监视:深入了解Vue3响应式系统的核心功能(下)
【Vue3】学习watch监视:深入了解Vue3响应式系统的核心功能(上)
【Vue3】学习watch监视:深入了解Vue3响应式系统的核心功能(上)
|
4月前
|
存储
Vue3 实现 PDF 文件在线预览功能
Vue3 实现 PDF 文件在线预览功能
360 0
|
4月前
|
JavaScript
VUE组件:什么是Vue的功能组件?
VUE组件:什么是Vue的功能组件?
46 5
|
4月前
|
JSON JavaScript 前端开发
VUE&Element,能够进行简单的 Element 页面修改, 能够完成查询所有功能, 能够完成添加功能
VUE&Element,能够进行简单的 Element 页面修改, 能够完成查询所有功能, 能够完成添加功能
36 0
|
1天前
|
JavaScript
vue3表格编辑(数据回显)和删除功能实现
vue3表格编辑(数据回显)和删除功能实现
6 1
|
2天前
|
存储 JavaScript 前端开发
使用vue实现一个添加和编辑的功能
使用vue实现一个添加和编辑的功能
9 1