Vue实现简易购物车功能(初学篇拿来即用)

1.引入一个vue文件

  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
​​​​​​​购物车原理:
  1. 数据定义:在Vue中,我们通过data选项定义购物车所需的数据,例如商品列表、商品数量、总价等。

  2. 数据绑定:使用Vue的模板语法将定义的数据与HTML模板进行绑定,将数据动态展示在页面上。通过插值表达式{{}}、指令v-bindv-for等,在HTML中引用购物车数据。

  3. 事件绑定:使用Vue的事件绑定机制,例如@clickv-on等,将组件中定义的方法与HTML元素上的事件进行关联。通过绑定事件,可以触发特定的逻辑操作,例如添加商品、删除商品、编辑商品等。

  4. 数据响应:Vue会自动追踪数据的变化,并在数据改变时更新对应的视图。当购物车数据发生变化,例如商品数量增加、价格计算等,Vue会自动重新渲染相关的视图部分,保持数据和视图的同步。

  5. 方法调用:在Vue组件中,我们可以定义一系列的方法来处理购物车的逻辑操作。例如添加商品、删除商品、编辑商品等操作,通过调用这些方法来更新购物车的数据和视图。

  6. 计算属性和监听器:Vue还提供了计算属性和监听器的功能,用于处理一些复杂的逻辑计算和数据侦听。例如根据商品数量和价格计算总价,可以使用计算属性来实现。

  1. HTML部分:
  • 使用<div id="shopping">包裹整个购物车的内容。
  • 使用<table>标签创建一个表格,用于展示购物车中的商品信息。
  • 在表格中使用v-for指令遍历list数组,生成每个商品的一行。
  • 使用{{}}插值语法绑定数据,显示商品的id、类型、价格、数量等信息。
  • 在最后一行添加统计信息,显示总价和总数。
  • 添加两个按钮,通过@click绑定方法,用于添加商品和编辑商品。
  1. Vue部分:
  • data中定义了购物车所需的数据:
    • add_status:控制添加商品按钮的显示与隐藏。
    • but_status:控制添加商品输入框的显示与隐藏。
    • edit_status:控制编辑商品输入框的显示与隐藏。
    • inp_idinp_nameinp_price:保存用户输入的商品信息。
    • countsprices:保存购物车中商品的总数和总价。
    • list:表示购物车中的商品列表,包含每个商品的id、名称、价格、数量和背景颜色。
  • methods中定义了购物车相关的方法:
    • add:增加商品数量,并更新总数和总价。
    • reduce:减少商品数量,并更新总数和总价。
    • add_prod:显示添加商品输入框。
    • add_hide:隐藏添加商品输入框。
    • edit:显示编辑商品输入框,并将对应商品的信息填充到输入框中。
    • edit_hide:隐藏编辑商品输入框。
    • product:添加新商品到购物车,并清空输入框。
    • colse:删除指定索引的商品,并更新总数和总价。
    • send_edit:保存编辑后的商品信息,并更新总数和总价。

 

 普通写法:

 <div id="shopping">
        <table border="10">
            <thead>
                <tr >
                    <th>id</th>
                    <th>类型</th>
                    <th>价格</th>
                    <th>数量</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item,index) in list" :style="item.color">
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>¥{{item.price}}</td>
                    <td><button @click="reduce(index)" v-show="list[index].count!=0">-</button>&nbsp&nbsp&nbsp{{item.count}}&nbsp&nbsp&nbsp<button @click="add(index)">+</button></td>
                    <td><button @click="edit(index)">编辑</button>
						<button @click="colse(index)">删除</button>
                    </td>
                </tr>
                <tr>
					<td></td>
                    <td></td>
					<td>总价:¥{{prices}}</td>
					<td>总数:{{counts}}</td>
					<td></td>
				</tr>
            </tbody>
        </table>
        <button @click="add_prod()" v-show="add_status==true">添加商品</button>
        <div v-show="but_status== true">
            衬衣序号:<input type="number" v-model="inp_id">
            衬衣品牌:<input type="text"  v-model="inp_name">
            衬衣价格:<input type="number" v-model="inp_price">
            &nbsp; &nbsp;<button @click="product()">添加</button>&nbsp;<button @click="add_hide()">取消</button>
        </div>
        <div v-show="edit_status== true" >
            衬衣序号:<input type="number" v-model="inp_id">
            衬衣品牌:<input type="text" v-model="inp_name">
            衬衣价格:<input type="number" v-model="inp_price">
            &nbsp; &nbsp;<button @click="send_edit()">确认编辑</button>&nbsp;<button @click="edit_hide()">取消</button>
        </div>
    </div>
    <script>
       Vue.createApp({
            data(){
                return {
                    add_status:true,
                    but_status:false,
                    edit_status:false,
                    inp_id: "",
					inp_name: "",
                    inp_price:"",
                    counts:0,
                    prices:0,
                    list: [{
						id: "1",
						name: "菠萝牌",
						price: "18",
                        count:0,
                        color: {
							background: ""
						},
					}, {
						id: "2",
						name: "香蕉牌",
						price: "699",
                        count:0,
                        color: {
							background: ""
						},
					}, {
						id: "3",
						name: "榴莲牌",
						price: "8",
                        count:0,
                        color: {
							background: ""
						},
					}]
                }
            },
            methods: {
				add(index) {
				    this.list[index].count++;
                    if (this.list[index].count > 0) {
                        console.log(this.list[index]);
						this.list[index].color.background = "#DFE7E7";
					}
                    let nam = 0;
                    for (let i = 0; i < this.list.length; i++) {
				      nam += this.list[i].count;
				    };
                    this.counts = nam;
                   
                    let pri = 0;
                    for (let i = 0; i < this.list.length; i++) {
                        pri += this.list[i].price * this.list[i].count;
				    };
                   
                    this.prices = pri;
                },
                reduce(index){
                    this.list[index].count--;
                    if (this.list[index].count == 0) {
                        console.log(this.list[index]);
						this.list[index].color.background = "";
					}
                    let nam = 0;
                    for (let i = 0; i < this.list.length; i++) {
				      nam += this.list[i].count;
				    };
                    this.counts = nam;
                   
                    let pri = 0;
                    for (let i = 0; i < this.list.length; i++) {
                        pri += this.list[i].price * this.list[i].count;
				    };
                    this.prices = pri;
                },
                add_prod(){
                    this.add_status = false;
                    this.but_status = true;
                },
                add_hide(){
                    this.but_status = false;
                    this.add_status = true;
                },
                edit(index){
                    console.log(index);
                    this.but_status = false;
                    this.edit_status=true;
                    this.add_status = false;
                    this.inp_id=this.list[index].id;
                    this.inp_name=this.list[index].name;
                    this.inp_price=this.list[index].price;
                    sessionStorage.setItem("index",index)
                },
                edit_hide(){
                    this.edit_status=false;
                    this.add_status = true; 
                    this.inp_id="";
                    this.inp_name="";
                    this.inp_price="";
                },
                product(){
                    this.list.push({
                        id:this.inp_id,
                        name:this.inp_name,
                        price:this.inp_price,
                        count:"0",
                        color: {
							background: ""
						},
                    })
                    this.but_status = false;
                    this.add_status = true;
                    this.inp_id="";
                    this.inp_name="";
                    this.inp_price="";
                },
                colse(index){
                    this.list.splice(index, 1);
                    let nam = 0;
                    for (let i = 0; i < this.list.length; i++) {
				      nam += this.list[i].count;
				    };
                    this.counts = nam;
                   
                    let pri = 0;
                    for (let i = 0; i < this.list.length; i++) {
                        pri += this.list[i].price * this.list[i].count;
				    };
                   
                    this.prices = pri;
                },
                send_edit(){
                   let index = sessionStorage.getItem("index")
                    this.list[index].id=this.inp_id;
                    this.list[index].name=this.inp_name;
                    this.list[index].price=this.inp_price;
                    this.edit_status=false;
                    this.add_status = true; 
                    this.inp_id="";
                    this.inp_name="";
                    this.inp_price="";
                    let nam = 0;
                    for (let i = 0; i < this.list.length; i++) {
				      nam += this.list[i].count;
				    };
                    this.counts = nam;
                    let pri = 0;
                    for (let i = 0; i < this.list.length; i++) {
                        pri += this.list[i].price * this.list[i].count;
				    };
                   
                    this.prices = pri;
                },
            },
        }).mount('#shopping')
    </script>

setup写法:

<script>
import { ref, reactive } from 'vue';

export default {
  setup() {
    const add_status = ref(true);
    const but_status = ref(false);
    const edit_status = ref(false);
    const inp_id = ref("");
    const inp_name = ref("");
    const inp_price = ref("");
    const counts = ref(0);
    const prices = ref(0);
    const list = reactive([
      {
        id: "1",
        name: "菠萝牌",
        price: "18",
        count: 0,
        color: {
          background: ""
        }
      },
      {
        id: "2",
        name: "香蕉牌",
        price: "699",
        count: 0,
        color: {
          background: ""
        }
      },
      {
        id: "3",
        name: "榴莲牌",
        price: "8",
        count: 0,
        color: {
          background: ""
        }
      }
    ]);

    const add = (index) => {
      list[index].count++;
      if (list[index].count > 0) {
        list[index].color.background = "#DFE7E7";
      }
      let nam = 0;
      for (let i = 0; i < list.length; i++) {
        nam += list[i].count;
      }
      counts.value = nam;

      let pri = 0;
      for (let i = 0; i < list.length; i++) {
        pri += list[i].price * list[i].count;
      }

      prices.value = pri;
    };

    const reduce = (index) => {
      list[index].count--;
      if (list[index].count === 0) {
        list[index].color.background = "";
      }
      let nam = 0;
      for (let i = 0; i < list.length; i++) {
        nam += list[i].count;
      }
      counts.value = nam;

      let pri = 0;
      for (let i = 0; i < list.length; i++) {
        pri += list[i].price * list[i].count;
      }

      prices.value = pri;
    };

    const add_prod = () => {
      add_status.value = false;
      but_status.value = true;
    };

    const add_hide = () => {
      but_status.value = false;
      add_status.value = true;
    };

    const edit = (index) => {
      but_status.value = false;
      edit_status.value = true;
      add_status.value = false;
      inp_id.value = list[index].id;
      inp_name.value = list[index].name;
      inp_price.value = list[index].price;
      sessionStorage.setItem("index", index);
    };

    const edit_hide = () => {
      edit_status.value = false;
      add_status.value = true;
      inp_id.value = "";
      inp_name.value = "";
      inp_price.value = "";
    };

    const product = () => {
      list.push({
        id: inp_id.value,
        name: inp_name.value,
        price: inp_price.value,
        count: "0",
        color: {
          background: ""
        }
      });
      but_status.value = false;
      add_status.value = true;
      inp_id.value = "";
      inp_name.value = "";
      inp_price.value = "";
    };

    const colse = (index) => {
      list.splice(index, 1);
      let nam = 0;
      for (let i = 0; i < list.length; i++) {
        nam += list[i].count;
      }
      counts.value = nam;

      let pri = 0;
      for (let i = 0; i < list.length; i++) {
        pri += list[i].price * list[i].count;
      }

      prices.value = pri;
    };

    const send_edit = () => {
      let index = sessionStorage.getItem("index");
      list[index].id = inp_id.value;
      list[index].name = inp_name.value;
      list[index].price = inp_price.value;
      edit_status.value = false;
      add_status.value = true;
      inp_id.value = "";
      inp_name.value = "";
      inp_price.value = "";
      let nam = 0;
      for (let i = 0; i < list.length; i++) {
        nam += list[i].count;
      }
      counts.value = nam;

      let pri = 0;
      for (let i = 0; i < list.length; i++) {
        pri += list[i].price * list.count;
      }

      prices.value = pri;
    };

    return {
      add_status,
      but_status,
      edit_status,
      inp_id,
      inp_name,
      inp_price,
      counts,
      prices,
      list,
      add,
      reduce,
      add_prod,
      add_hide,
      edit,
      edit_hide,
      product,
      colse,
      send_edit
    };
  }
};
</script>

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,下面是一个简单使用Vue.js制作购物车效果的示例: 首先,创建一个Vue实例: ``` var app = new Vue({ el: '#app', data: { products: [ { id: 1, name: 'iPhone X', price: 999.99, quantity: 0 }, { id: 2, name: 'iPad Pro', price: 799.99, quantity: 0 }, { id: 3, name: 'MacBook Pro', price: 1499.99, quantity: 0 } ], cart: [] }, methods: { addToCart: function(product) { if(product.quantity > 0) { var index = this.cart.findIndex(item => item.id === product.id); if(index >= 0) { this.cart[index].quantity += product.quantity; } else { this.cart.push({ id: product.id, name: product.name, price: product.price, quantity: product.quantity }); } product.quantity = 0; } }, removeFromCart: function(product) { var index = this.cart.findIndex(item => item.id === product.id); if(index >= 0) { this.products.find(item => item.id === product.id).quantity += this.cart[index].quantity; this.cart.splice(index, 1); } }, getTotal: function() { var total = 0; this.cart.forEach(item => { total += item.price * item.quantity; }); return total.toFixed(2); } } }); ``` 在这里,我们定义了一个包含商品和购物车的数据对象。商品包括ID、名称、价格和数量属性,而购物车仅包括ID、名称、价格和数量属性。我们还定义了三个方法: - addToCart:将商品添加到购物车中,然后将其数量重置为0。 - removeFromCart:从购物车中删除商品,并将其数量添加回商品列表中。 - getTotal:计算购物车中所有商品的总价值。 接下来,我们可以在Vue模板中使用这些数据和方法来创建购物车效果: ``` <div id="app"> <div class="product-list"> <div v-for="product in products" :key="product.id"> <h3>{{ product.name }}</h3> <p>{{ product.price | currency }}</p> <input type="number" v-model.number="product.quantity" min="0" max="10"> <button @click="addToCart(product)">Add to Cart</button> </div> </div> <div class="cart"> <h2>Shopping Cart</h2> <div v-for="product in cart" :key="product.id"> <h3>{{ product.name }}</h3> <p>{{ product.price | currency }}</p> <input type="number" v-model.number="product.quantity" min="0" max="10"> <button @click="removeFromCart(product)">Remove from Cart</button> </div> <p>Total: {{ getTotal() | currency }}</p> </div> </div> ``` 在这里,我们使用v-for指令来遍历商品列表和购物车,并使用v-model指令来绑定商品数量输入框和购物车数量输入框。我们还使用过滤器来格式化价格和总价值。最后,我们使用@click指令来触发添加和删除商品的事件。 这是一个简单购物车示例,你可以根据自己的需要进行修改和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

代码真的养发

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

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

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

打赏作者

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

抵扣说明:

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

余额充值