vuex——做简单的购物车功能

购物车组件

<template>
    <div>
        <h1>vuex-shopCart</h1>
        <div class="shop-listbox">
            <shop-list/>
        </div>
        <h2>已选商品</h2>
        <div class="shop-cartbox">
            <shop-cart/>
        </div>
    </div>
</template>

<script>

    import shopList from "./shop-list";
    import shopCart from './shop-cart';

    export default{
        name:'shop',
        components:{
            'shop-list':shopList,
            'shop-cart':shopCart
        }

    }
</script>

商品列表

<template>
    <div class="shop-list">
        <table>
            <tr class="shop-listtitle">
                <td>id</td>
                <td>名称</td>
                <td>价格</td>
                <td>操作</td>
            </tr>
            <tr v-for="item in shopList" class="shop-listinfo">
                <td>{{item.id}}</td>
                <td>{{item.name}}</td>
                <td>{{item.price}}</td>
                <td><button @click="addToCart(item)">加入购物车</button></td>
            </tr>
        </table>
    </div>
</template>

<script>
    import{mapActions} from "vuex";
    export default{
        name:'shopList',
        data(){
            return{

            }
        },
        computed:{
            shopList(){
                return this.$store.getters.getShopList
            }
        },
        methods:{
            ...mapActions(['addToCart'])
        }
    }
</script>
<style lang="less" scoped>
    @import url('../../static/public.less');
</style>

选中商品列表

<template>
    <div class="shop-list">
        <table>
            <tr class="shop-listtitle">
                <td>id</td>
                <td>名称</td>
                <td>价格</td>
                <td>数量</td>
                <td>操作</td>
            </tr>
            <tr v-for="item in cartData" class="shop-listinfo">
                <td>{{item.id}}</td>
                <td>{{item.name}}</td>
                <td>{{item.price}}</td>
                <td>{{item.num}}</td>
                <td><button class="shop-dele dele-btn" @click="deletShop(item)">删除</button></td>
            </tr>
            <tr v-if="cartData.length<=0">
                <td colspan="5">暂无数据</td>
            </tr>
            <tr>
                <td colspan="2">总数:{{totalNum}}</td>
                <td colspan="2">总价格:{{totalPrice}}</td>
                <td><button class="dele-cart dele-btn" @click="clearCart">清空购物车</button></td>
            </tr>
        </table>
    </div>
</template>

<script>
    import {mapGetters,mapActions} from "vuex";
    export default{
        name:'shopCart',
        data(){
            return{
                
            }
        },
        computed:{
            ...mapGetters({
                cartData:'addShopList',
                totalNum:'totalNum',
                totalPrice:'totalPrice'
            })
        },
        methods:{
            ...mapActions({
                clearCart:'clearToCart',
                deletShop:'deletToShop'
            })
        }
    }
</script>

<style lang="less" scoped>
    @import url('../../static/public.less');
    .dele-btn{
        background-color: red !important;
    }
    .dele-btn:hover{
        background-color: #bd0000 !important;
    }
</style>

vuex 创建

npm install vuex --save,创建vuex文件夹,在文件夹中创建store.js,引入vuex;

import Vue from "vue";
import Vuex from 'vuex';
import cart from "./modules/cart";


Vue.use(Vuex);

export default new Vuex.Store({
    modules:{
        cart
    }
})

建立一个模块文件夹modules,里面创建创建当个store模块,然后默认输出,在store.js中引入;

const state = {
    shop_list: [{
        id: 11,
        name: '鱼香肉丝',
        price: 12,
    }, {
        id: 22,
        name: '宫保鸡丁',
        price: 14
    }, {
        id: 34,
        name: '土豆丝',
        price: 10
    }, {
        id: 47,
        name: '米饭',
        price: 2
    },{
        id: 49,
        name: '蚂蚁上树',
        price: 13
    },
    {
        id: 50,
        name: '腊肉炒蒜薹',
        price: 15
    }],
    add:[]
}

const getters ={
    //获取商品列表
    getShopList:state => state.shop_list,
    //获取购物车列表
    addShopList:state => {
        return state.add.map(({id,num})=>{
            let product = state.shop_list.find(n => n.id == id);
            if(product){
                return{
                    ...product,
                    num
                }
            }
        })
    },
    //获取总数量
    totalNum:(state,getters) =>{
        let total =0;
        getters.addShopList.map(n=>{
            total += n.num;
        })
        return total;
    },
    //计算总价格
    totalPrice:(state,getters)=>{
        let total=0;
        getters.addShopList.map(n=>{
            total += n.num*n.price
        })
        return total;
    },

}

const actions={
    //加入购物车
    addToCart({commit},product){
        commit('addCart',{
            id:product.id
        })
    },
    //清空购物车
    clearToCart({commit}){
        commit('clearCart')
    },
    //删除单个物品
    deletToShop({commit},product){
        commit('deletShop',product)
    }
}

const mutations ={
    //加入购物车
    addCart(state,{id}){
        let record = state.add.find(n => n.id == id);
        if(!record){
            state.add.push({
                id,
                num:1
            })
        }else{
            record.num++;
        }
    },
    //删除单个物品
    deletShop(state,product){
        state.add.forEach((item,i)=>{
            if(item.id == product.id){
                state.add.splice(i,1)
            }
        })

    },
    //清空购物车
    clearCart(state){
        state.add=[];
    }
}

export default{
    state,
    getters,
    actions,
    mutations
}

 

转载于:https://www.cnblogs.com/huangmin1992/p/8717003.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vuex 是一个专为 Vue.js 应用程序设计的状态管理模式,它提供了一种集中存储和管理应用组件之间共享状态的方式。在实现购物车功能时,Vuex 可以帮助我们在单页应用中保持购物车的状态(如商品列表、数量、总价等),并且使得这些状态在整个应用中都是响应式的。 下面是使用 Vuex 实现购物车功能的基本步骤: 1. 定义状态 (state): 在 `store` 中创建一个购物车的状态对象,包含商品列表 (`cartItems`)、总数量 (`cartCount`) 和总价 (`cartTotal`)。 ```javascript state: { cartItems: [], cartCount: 0, cartTotal: 0 }, ``` 2. 定义 mutations (改变状态的方法): 用来更新购物车状态的函数。例如,添加商品 (`ADD_TO_CART`)、从购物车移除商品 (`REMOVE_ITEM`)、更新数量 (`UPDATE_ITEM_QUANTITY`)。 ```javascript mutations: { ADD_TO_CART(state, item) { state.cartItems.push(item); state.cartCount++; state.cartTotal += item.price; }, REMOVE_ITEM(state, index) { state.cartItems.splice(index, 1); state.cartCount--; state.cartTotal -= state.cartItems[index].price; }, UPDATE_ITEM_QUANTITY(state, { index, quantity }) { state.cartItems[index].quantity = quantity; state.cartTotal = calculateCartTotal(state.cartItems); } }, ``` 3. 计算总价 (getters): 为了高效地获取购物车总价,我们可以创建一个getter函数 (`calculateCartTotal`),根据商品列表计算总价。 ```javascript getters: { calculateCartTotal(state) { return state.cartItems.reduce((total, item) => total + item.price * item.quantity, 0); } }, ``` 4. 使用 actions (异步操作): 当需要从后端获取商品信息或者处理复杂的业务逻辑时,可以定义 actions。例如,`FETCH_CART_ITEMS` 和 `UPDATE_CART_ITEM`。 5. 配置 actions: 在 actions 中调用 API 或者执行其他异步操作,然后触发对应的 mutations 更新状态。 6. 创建 getters 和 actions 之后,你可以在 Vue 组件中通过 `mapState` 和 `mapActions` 来读取状态和触发操作。 ```vue <template> <div> <!-- 商品列表 --> <ul> <li v-for="(item, index) in cartItems" :key="index"> {{ item.name }} - {{ item.quantity }} x {{ item.price }} <button @click="removeItem(index)">Remove</button> </li> </ul> <p>Total: {{ cartTotal }}</p> </div> </template> <script> import { mapState, mapActions } from 'vuex'; export default { computed: { ...mapState(['cartItems', 'cartTotal']) }, methods: { ...mapActions(['REMOVE_ITEM', 'UPDATE_ITEM_QUANTITY']) } }; </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值