购物车,数量的增减

本文将探讨如何使用JavaScript和TypeScript在前端实现购物车中商品数量的增加与减少功能,包括交互逻辑和状态管理。
摘要由CSDN通过智能技术生成

还没体现

import {
    createStore } from 'vuex'
import books from '@/data/books.js'

const store = createStore({
   
    state() {
   
        return {
   
            items: books 
        }
    },
    mutations: {
   
        pushItemToCart (state, book) {
   
            state.items.push(book);
        },
    deleteItem(state, id) {
   
        let index = state.items.findIndex(item => item.id ===id);
        if(index >= 0) {
   
            state.items.splice(index, 1)
        }
    },
    incrementItemCount(state, {
   id, count}) {
   
        let item = state.items.find(item => item.id === id);
        if(item) {
   
            item.count += count;
        }
    }
    },
    getters: {
   
        cartItemPrice(state) {
   
            return function(id) {
   
                let item = state.items.find(item => item.id === id);
                if(item) {
   
                    return item.price * item.count;
                }
            }
        },
        cartTotalPrice(state) {
   
            return state.items.reduce((total, item) => {
   
                return total + item.price * item.count;
            }, 0)
        }
    }
})

export default store
<template>
  <div>
      <table>
          <tr>
              <td>商品编号</td>
              <td><input type="text" v-model.number="id"></td>
          </tr>
          <tr>
              <td>商品名称</td>
              <td><input type="text" v-model="title"></td>
          </tr>
          <tr>
              <td>商品价格</td>
              <td><input type="text" v-model="price"></td>
          </tr>
          <tr>
              <td colspan="2"><button @click="addCart">加入购物车</button></td>
          </tr>
      </table>
      <table>
          <thead>
              <tr>
                  <th>编号</th>
                  <th>商品名称</th>
                  <th>价格</th>
                  <th>数量</th>
                  <th>金额</th>
                  <th>操作</th>
              </tr>
          </thead>
          <tbody
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值