微信小程序(黑马优购:加入购物车)

1.配置Vuex

1).创建store.js目录

复制代码
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules:{}
})

export default store

2).pages.json中配置

复制代码
import store from '@/store/store.js'



const app = new Vue({
    ...App,
    ///挂载
    store
})

3).配置cart.js

复制代码
export default{
  namespaced: true,
  
  state: ()=> ({
    //购物车的数组,用来存储购物车中每个商品的信息对象
    //每个商品的信息对象,都包含如下6个属性
    //{goods_id,goods_name,goods_price,goods_count,goods_small_logo,goods_state}
    cart: []
  }),
  
  mutations: {
    
  },
  
  getters: {
    
  }
  
  
}

store.js中引入cart.js

复制代码
import Vue from 'vue'
import Vuex from 'vuex'
import moduleCart from '@/store/cart.js'


Vue.use(Vuex)

const store = new Vuex.Store({
  modules:{
    
    'm_cart': moduleCart
    
  }
})

export default store

2.把cart.js的cart数组到当前页面

复制代码
import { mapState } from 'vuex'
  
  
  export default {
    computed: {
        ...mapState('m_cart',['cart'])
    },

3.定义addToCart对象

cart.js

复制代码
export default{
  namespaced: true,
  
  state: ()=> ({
    //购物车的数组,用来存储购物车中每个商品的信息对象
    //每个商品的信息对象,都包含如下6个属性
    //{goods_id,goods_name,goods_price,goods_count,goods_small_logo,goods_state}
    cart: []
  }),
  
  mutations: {
    addToCart(state,goods){
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      
      if(!findResult){
        state.cart.push(goods)
      }else{
        findResult.goods_count++
      }
      
    }
  },
  
  getters: {
    
  }
}

4.在goods_detail.vue中调用

复制代码
import { mapState, mapMutations } from 'vuex'

    methods: {
      ...mapMutations('m_cart'),

1)调用cart.js中的addToCart

复制代码
 methods: {
      ...mapMutations('m_cart',['addToCart']),

5.定义getters

复制代码
 getters: {
    total(state){
      let c = 0
      state.cart.forEach(x => c += x.goods_count)
      return c
    }

1)在goods_detail中进行映射

复制代码
  //定义一个监听器
    watch:{
      //1.监听total值的变化,通过第一个形参得到变化后的新值
        total(newVal){
          //2.通过数组的find()方法,找到购物车按钮的配置对象
          const findResult = this.options.find(x => x.text === '购物车')
          if(findResult){
            //3.动态为购物车按钮的info属性赋值
            findResult.info = newVal
          }
        }
    },

6.持久化存储购物车的商品

复制代码
export default{
  namespaced: true,
  
  state: ()=> ({
    //购物车的数组,用来存储购物车中每个商品的信息对象
    //每个商品的信息对象,都包含如下6个属性
    //{goods_id,goods_name,goods_price,goods_count,goods_small_logo,goods_state}
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  
  mutations: {
    addToCart(state,goods){
      //根据提交的商品的id,查询购物车中是否存在这件商品
      //如果不存在,则findResult为undefined;否则,为查找到的商品信息对象
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      
      if(!findResult){
        //如果购物车中没有这件商品,则直接push
        state.cart.push(goods)
      }else{
        //如果购物车中有这件商品,则只更新数量即可
        findResult.goods_count++
      }
      //通过commit方法,调用m_cart命名空间的saveToStorage方法
      this.commit('m_cart/saveToStorage')
      
    },
    
    saveToStorage(state){
        uni.setStorageSync('cart',JSON.stringify(state.cart))
    }
  },

  getters: {
    total(state){
      let c = 0
      state.cart.forEach(x => c += x.goods_count)
      return c
    }
  }
}

7.优化商品详情页的total侦听器

这样可以确保一刷新就加载购物车数

复制代码
 //定义一个监听器
    watch:{
      //1.监听total值的变化,通过第一个形参得到变化后的新值
        // total(newVal){
        //   //2.通过数组的find()方法,找到购物车按钮的配置对象
        //   const findResult = this.options.find(x => x.text === '购物车')
        //   if(findResult){
        //     //3.动态为购物车按钮的info属性赋值
        //     findResult.info = newVal
        //   }
        // }
        total: {
          handler(newVal){
            const findResult = this.options.find(x => x.text === '购物车')
            if(findResult){
              findResult.info = newVal
            }
          },
          //immediate属性用来声明次侦听器,是否在页面初次加载完毕后立即调用
          immediate: true
        }
    },

8.点击商品详情页购物车图标跳转到购物车页面

复制代码
<template>
  <view>
    cart
  </view>
</template>

<script>
  import { mapGetters } from 'vuex'
  
  
  export default {
    //计算属性
    computed: {
        ...mapGetters('m_cart',['total'])
    },
    onShow(){
        this.setBadge()
    },
    data() {
      return {
        
      }
    },
    methods: {
      setBadge(){
        uni.setTabBarBadge({
          index:2,
          text: this.total + ''
        })
      }
    }
  }
</script>

<style>

</style>

9.创建minixs目录进行封装

tabbar-badage.js配置,减少重复代码

复制代码
import { mapGetters } from 'vuex'

 
  export default {
    //计算属性
    computed: {
        ...mapGetters('m_cart',['total'])
    },
    onShow(){
        this.setBadge()
    },
    
    methods: {
      setBadge(){
        uni.setTabBarBadge({
          index:2,
          text: this.total + ''
        })
      }
    }
  }

cart.vue页面配置,(其他tabbar页面也是同样配置)

复制代码
<template>
  <view>
    cart
  </view>
</template>

<script>
  
  import badgeMix from '@/mixins/tabbar-badge.js'
  
  export default {
    mixins: [badgeMix],
    data() {
      return {

      }
    }

  }
</script>

<style>

</style>
相关推荐
梓彤科技11 小时前
登录状态总是失效,武汉小程序开发怎样设计会话续期与接口鉴权?
微信小程序·小程序·登录鉴权
黑马程序员毕设11 小时前
非遗文化展览系统设计与实现
人工智能·spring boot·后端·微信小程序·毕设
维双云12 小时前
专业开发小程序公司有哪些:从项目交付能力判断服务商
小程序
show43313 小时前
2026多格式导出技术方案:小程序端免费TXT/Word/SRT生成实践
小程序·word
维双云1 天前
社区生鲜小程序怎么做?4个经营环节。
小程序·零售
2601_949950631 天前
成绩提升不靠盲目刷题:用练题簿找准真正的薄弱知识点
学习·小程序·刷题·小程序推荐
今日热点1 天前
微信小程序主体变更公证全流程实操解析:场景条件、材料规范、驳回避坑与Python校验脚本实现
python·微信小程序·小程序
Buke..1 天前
【小程序逆向】某游快爆 AI 逆向 sign参数:AI 辅助分析与 MCP 工具链实战
前端·人工智能·爬虫·python·小程序·notepad++
T01156181 天前
艺培场馆课时预约小程序用户端 & 后台联动踩坑上篇(预约、课时、缓存、消息、学员端自身问题)
java·缓存·小程序·bug·全栈项目实战手记·艺培课时系统‘’