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

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>
相关推荐
hmz8565 分钟前
最新网课搜题答案查询小程序源码/题库多接口微信小程序源码+自带流量主
前端·微信小程序·小程序
小雨cc5566ru3 小时前
uniapp+Android智慧居家养老服务平台 0fjae微信小程序
android·微信小程序·uni-app
计算机学姐4 小时前
基于微信小程序的调查问卷管理系统
java·vue.js·spring boot·mysql·微信小程序·小程序·mybatis
正小安11 小时前
如何在微信小程序中实现分包加载和预下载
前端·微信小程序·小程序
说私域11 小时前
基于定制开发与2+1链动模式的商城小程序搭建策略
大数据·小程序
丁总学Java17 小时前
微信小程序-npm支持-如何使用npm包
前端·微信小程序·npm·node.js
工业互联网专业18 小时前
毕业设计选题:基于ssm+vue+uniapp的校园水电费管理小程序
vue.js·小程序·uni-app·毕业设计·ssm·源码·课程设计
说私域1 天前
社群团购中的用户黏性价值:以开源小程序多商户AI智能名片商城源码为例
人工智能·小程序
迷雾yx1 天前
开发微信小程序 基础02
微信小程序·小程序
迷雾yx1 天前
开发微信小程序 基础03
微信小程序·小程序