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

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>
相关推荐
萧寂1732 小时前
微信小程序自定义轮播图指示点样式
微信小程序·小程序
SuperherRo10 小时前
自动化反编译微信小程序工具-e0e1-wx
微信小程序·自动化·hook·反编译
R_yy11 小时前
微信小程序开发——视频播放实现(本地视频或者云端视频均可)
前端·微信小程序·小程序
京河小蚁13 小时前
解决Moodo调节心情模块-大声喊出来无法测量出音频分贝
微信小程序·音视频·ai编程·cursor
低代码布道师15 小时前
加油站小程序实战教程03站点管理
低代码·小程序
蒜香拿铁15 小时前
小程序参数获取方式
前端·微信小程序
V+zmm1013418 小时前
智慧物流小程序(论文源码调试讲解)
java·数据库·微信小程序·小程序·毕业设计
霍格沃兹测试开发学社测试人社区18 小时前
性能测试丨微信小程序性能优化指南
性能优化·微信小程序·小程序
猿毕设21 小时前
【FL0100】基于SSM微信小程序的走失人员的报备平台
java·spring boot·后端·python·微信小程序·小程序
猿毕设21 小时前
【FL0091】基于SSM和微信小程序的社区二手物品交易小程序
java·spring boot·后端·python·微信小程序·小程序