首页 > 语言 > JavaScript > 正文

vuex实现的简单购物车功能示例

2024-05-06 15:42:28
字体:
来源:转载
供稿:网友

本文实例讲述了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>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选