vue购物车/vuex/vue-router

本文详细讲解如何在Vue项目中实现购物车功能,结合Vuex进行状态管理,以及如何利用Vue-Router进行页面间的导航。通过实例展示如何在点击商品时将商品信息添加到购物车,并在不同路由间保持购物车状态的一致性。
摘要由CSDN通过智能技术生成
//store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export const store = new Vuex.Store({
    strict: true,
    state: {
        cart: JSON.parse(localStorage.getItem('cart')) || []
    },
    getters:{
        totalMoney(state){
         return state.cart.reduce((a,b)=>{
           return a+b.price*b.count
         },0)
        }
    },
    mutations: {
        addItem(state, obj) {
     let result = state.cart.find(item => item.id == obj.id)
            if (result) {
                result.count++
            } else {
                state.cart.unshift({ ...obj, count: 1 })
            }
        },
        addCount(state,obj){
         let index=state.cart.findIndex(item=>item.id==obj.id)
         state.cart[index].count++
        },
        downCount(state,obj){
            let index=state.cart.findIndex(item=>item.id==obj.id)
            if (state.cart[index].count>1) {
                state.cart[index].count--
            }}}})
store.subscribe((mutation,state)=>{
    console.log(mutation)//{type: "addItem", payload: {…}}
    localStorage.setItem('cart',JSON.stringify(state .cart))})
    ```
 ```javascript
 import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

 
import h from '@/components/home.vue'
import c from '@/components/cart.vue'
import l from '@/components/list.vue'

const router = new VueRouter({
    mode:'history',
    routes:[
        {path:'/',redirect:'/h'},
        {path:'/home',component:h},
        {path:'/cart',component:c},
        {path:'/list',component:l},
    ]
})
export default router
//App.vue
  <template>
  <div id="app">
    <h2>商品IE</h2>
    <ul>
      <li v-for="(item) in goods" :key="item.id">
        {{item.title}}--{{item.price}}
        <button @click="fn(item)">添加购物车</button>
      </li>
    </ul>
    <h2>购物车</h2>
    <table border="1">
      <tr>
        <th>商品</th>
        <th>数量</th>
        <th>单价</th>
        <th>小计</th>
        <th>操作</th>
      </tr>
      <tr v-for="(item) in cart" :key="item.id">
        <td>{{item.title}}</td>
        <td>{{item.count}}</td>
        <td>{{item.price}}</td>
        <td>{{item.price*item.count}}</td>
        <td>
        <button @click="down(item)">-</button>
        <button @click="up(item)">+</button>
        </td>
      </tr>
    </table>
    <p>总计:{{counts}}</p>
  </div>
  </template>

<script>
export default {
  name: "App",
  computed: {
    counts(){
      return this.cart.reduce((a,b)=>{
        return a+b.price*b.count
      },0)} }, 
  methods: {
    up(item){
        item.count++  },
    down(item){
      if(item.count==0){
       return item.count=0
      }else{
       return item.count--  }},
    fn(item) {
      let result = this.cart.find(el=>el.id==item.id);
      if (result) {//找到返回对象 找不到返回undefined
        result.count++
      } else {
        // 响应,直接添加item.count=1,不响应
        this.cart.unshift({...item,count:1});
        // console.log(this.cart[0].count)
      }},},};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
//list.vue
<script>
import cart from "./cart";
export default {
  components: {cart},
  data() {
    return {
      goods: [
        { id: 0, title: "玛莎拉低", price: 100 },
        { id: 1, title: "保罗之家", price: 100 },
        { id: 2, title: "世界极地", price: 200 },
        { id: 3, title: "否极泰来", price: 999 },],
      cart: [],
    };},
  methods: {
    fn(item) {
      this.$store.commit('addItem',item)}}};
</script>
//cart.vue
<template>
  <div>
    <h2>购物车</h2>
    <table border="1">
      <tr>
        <th>商品</th><th>数量</th>
        <th>单价</th><th>小计</th>
        <th>操作</th>
      </tr>
      <tr v-for="(item) in bcart" :key="item.id">
        <td>{{item.title}}</td>
        <td>{{item.count}}</td>
        <td>{{item.price}}</td>
        <td>{{item.price*item.count}}</td>
        <td>
          <button @click="down(item)">-</button>
          <button @click="up(item)">+</button>
        </td>
      </tr> </table> <p>总计:{{counts}}</p>
  </div>
</template>
<script>
import {mapState,mapGetters} from 'vuex'
export default {
  computed: {
    ...mapState({
      bcart:'cart'}),
    ...mapGetters({
      counts:'totalMoney'}) },
  methods: {
    up(item) { this.$store.commit('addCount',item)},
    down(item) {
      this.$store.commit('downCount',item)
    },},};
    
</script>
//home.vue

<template>
  <div>
    <h2>这里是首页</h2>
    总价:{{counts}}
  </div>
</template>

<script>
import { mapGetters } from "vuex";

export default {
  computed: {
    ...mapGetters({       //方法一
      counts: "totalMoney",
    }),
  },
// computed: mapGetters({
//   counts:'totalMoney'   方法二
// })
// computed: {            方法三
//     counts(){
//         return this.$store.getters.totalMoney
//     }
// },
};
</script>

<style>
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值