本文實例講述了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>
新聞熱點
疑難解答
圖片精選