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

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>
相关推荐
2301_8059629322 分钟前
微信小程序控制空调之接收MQTT消息
微信小程序·小程序·esp32
The_era_achievs_hero23 分钟前
微信小程序121~130
微信小程序·小程序
難釋懷26 分钟前
微信小程序WXSS 模板样式
微信小程序·小程序·notepad++
清颖~28 分钟前
原生微信小程序研发,如何对图片进行统一管理?
微信小程序·小程序
军军君0138 分钟前
基于Springboot+UniApp+Ai实现模拟面试小工具二:后端项目搭建
前端·javascript·spring boot·spring·微信小程序·前端框架·集成学习
默魔6 小时前
uniapp 微信小程序点击开始倒计时
微信小程序·小程序·uni-app
阿俊-全栈开发18 小时前
crmeb多门店对接拉卡拉支付小程序聚合收银台集成全流程详解
小程序·php·拉卡拉聚合收银台·拉卡拉三方支付
難釋懷1 天前
微信小程序全局配置
微信小程序·小程序
Enti7c1 天前
微信小程序核心知识点速览
微信小程序·小程序
2501_915918412 天前
Fiddler中文版全面评测:功能亮点、使用场景与中文网资源整合指南
android·ios·小程序·https·uni-app·iphone·webview