Download Vuex

yarn add vuex -S
Copy the code

Create a folder named store/index.js under SRC

Add store/index.js to main.js and mount it

import store from './store'

new Vue({
    store
})
Copy the code

4. Use it in app. vue

Copy the code

Implement the shopping cart in the real project (mall_phone)

1. Lazy method: directly run: vue add vuex command, generate store folder and index.js file in SRC, import and mount them automatically, and index.js file will have default format

2. Realize the dynamic change of the quantity in the shopping cart in the bottom navigation of the home page

App.vue :badge=”$store.getters. GetAllCart “badge=”$store.getters.

  • App.vue
<van-tabbar-item
        icon="cart-o"
        to="/cart"
        :badge="$store.state.count"
      ></van-tabbar-item>
Copy the code
  • store/index.js
state: {
    count: 9
  }
Copy the code

2. On the basis of the previous step, implement dynamic change

  • First define a function in getters in store/index.js to calculate the count value and add a Cart property to state
getAllCart(state) {
      let c = 0
      // Count all items by traversing
      state.cart.forEach(item= > {
        c += item.count
      })
      return c
    }
Copy the code
state: {
    count: 0.// cart: JSON.parse(localStorage.cart || '[]')
    cart: JSON.parse(localStorage.getItem('cart') | |'[]')}Copy the code
  • App.vue
<van-tabbar-item
        icon="cart-o"
        to="/cart"
        :badge="$store.getters.getAllCart"
      ></van-tabbar-item>
Copy the code

3. Click to add to cart and obtain data information in Cart.vue

1. Add shopping cart button in GoodsInfo, add click event, trigger function, used to transfer product information

<van-button type="danger" size="small" @click="addCart"</van-button >Copy the code
addCart() {
      const goodsinfo = {
        id: this.id,
        src: this.lunbolist[0].src,
        price: this.goodsInfo.sell_price,
        title: this.goodsInfo.title,
        selected: true.count: this.value,
        timer: null
      }
      this.$store.commit('addCart', goodsinfo)/ / data
    }
Copy the code

2. Obtain product information from store/index.js and save the information locally

mutations: {
    addCart(state, goodsinfo) { // Receive data goodsinfo
    // If the item is added to the cart for the first time, push it to the list. If it is not added to the cart for the first time, just change its count value, so set a flag variable
      let flag = false
      state.cart.forEach(item= > {
        if (item.id === goodsinfo.id) {
          item.count += goodsinfo.count
          flag = true}})if(! flag) { state.cart.push(goodsinfo) }// console.log(goodsinfo)
      // Store it locally
      localStorage.setItem('cart'.JSON.stringify(state.cart))
    }
  },
Copy the code
  • Each time you define a function, you can print it to see if it receives the data before you implement it. For example, in the addCart function here, you can print console.log(goodsinfo) to see if it has any content (this will make it easier to find the problem and prevent the screen from being full of red).

3. After obtaining the value, render the product information to the page (cart.vue)

<template>
  <div class="cart">
    <div class="cart-list" v-for="item in $store.state.cart" :key="item.id">
      <div class="cart-l">/ / switch<van-switch v-model="item.selected" />
      </div>// Product information<div class="cart-r">
        <van-card
          :num="item.count"
          :price="item.price + '.00'"
          :title="item.title"
          :thumb="item.src"
        >// Add a stepper slot to add/subtract count (count is global, one change, all change)<div slot="desc" class="step">
            <van-stepper v-model="item.count" />
          </div>
        </van-card>
      </div>
    </div>// Submit the order component, and the total price can be dynamically changed<van-submit-bar
      :price="$store.getters.getAllPrice * 100"
      button-text="Submit order"
    />
  </div>
</template>
<script>
export default {
  data: () = >({})}</script>
<style lang="less">
.cart {
  width: 100%;
  padding: 10px;
  .cart-list {
    display: flex;
    border: 1px solid #e5e5e5;
    padding: 4px;
    margin-bottom: 10px;
    .cart-l {
      display: flex;
      flex: 1; / / in the middlealign-items: center;
      justify-content: center;
    }
    .cart-r {
      flex: 3;
      .step {
        margin: 10px; }}}}</style>

Copy the code

4. Realize total price changes

  • Functions are defined in getters in store/index.js to implement the total price
getAllPrice(state) {
      let price = 0
      // Count all items by traversing
      state.cart.forEach(item= > {
      // If the switch is closed, the price of the commodity will not be added
        if (item.selected === true) {
          price += item.count * item.price
        }
      })
      return price
    }
Copy the code
  • The total price is displayed at the place of order submission in Cart.vue
<van-submit-bar
      :price="$store.getters.getAllPrice * 100"
      button-text="Submit order"
    />
Copy the code