温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue如果实现购物车功能

发布时间:2022-03-07 15:28:03 来源:亿速云 阅读:189 作者:iii 栏目:web开发

本文小编为大家详细介绍“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">

    <h4>购物车</h4>

    名称:<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>

读到这里,这篇“vue如果实现购物车功能”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue
AI