Vue small project (2) - complete implementation of shopping cart

1 Basic knowledge that needs to be understood in advance

This project completely uses front-end development and does not use a server (front-end development partners can rest assured). The front-end uses: vue, vue-cli, vuex, vue-router, axios, ES6, ES Module and other technologies

2 Directory deployment

  1. Final implementation directory

Insert image description here

2 public directory
Because this project does not use a server, we store the data locally for easy access. list.json is the json file that needs to be obtained on the page later. The image resources under static/img/list are (can also be placed scr/assets/img), I will upload relevant resources later, you can download them
Insert image description here
3 src directory
Insert image description here
components components (payment component, product component)
views page (home page, product list page)
router.js routing
store .js store
App.vue application component
main.js The entry file
style/icofot stores Alibaba’s font icon files. Please click () for usage instructions.

3 effects

1 List page
Insert image description here
2 Shopping cart page
Insert image description here
3 To achieve the overall effect
Insert image description here

4 Specific functions implemented

  1. (Add to shopping cart) Select the product on the list page and add it to the shopping cart. Once added to the shopping cart, you cannot add it again. Clicking the button again will delete the product from the shopping cart.Insert image description here

  2. (Route conversion) After adding the shopping cart to the list page, click 'Enter the shopping cart page' below, and you can see the products added to the shopping cart. If there are no products in the shopping cart, you cannot enter the shopping cart page. Click on the shopping cart page. Head 'Shopping Cart' to return to the product list pageInsert image description here

  3. (Select all, single selection) On the shopping cart page, when you click the circle in the upper left corner of the product, it means the product you want to buy. Click it again to cancel the purchase. Clicking the select all at the bottom means all the products in the shopping cart page need to be purchased. Click again. Click to cancel all selections

  4. (Price calculation) Only after adding the product to the shopping cart and clicking to purchase the product can the price be settled.Insert image description here

  5. (Quantity added, quantity reduced) On the shopping cart page, click the + sign to add the product. Click the - sign to reduce the quantity of the product in the shopping cart. When the quantity is 1, click the - sign to remove the product from the shopping cart. Delete this product in

  6. (Remove from shopping cart) Click the trash can icon in the upper right corner of each product on the shopping cart page to remove the product from the shopping cart.Insert image description here

  7. (Local storage) Using local storage, if you refresh the page or reopen the page, the products previously added to the shopping cart are still there and cannot be re-selected.Insert image description here

5 Complete code implemented

Because there are many code contents and pages, in order to facilitate everyone's understanding, I have displayed all the codes in each file, with detailed comments for everyone to read. If you still don't understand, you can leave a message.

(1) main.js

Notice:

  1. The use of Ali vector font icons can be stamped
  2. element-ui Chinese official website: You can poke element-ui Chinese official website
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
// 引入element-ui
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

// 引入阿里字体图标
import '@/assets/style/iconfont/iconfont.css'
// 安装
Vue.prototype.$http = axios
Vue.use(ElementUI)

import {
   
    
     Message } from 'element-ui';
new Vue({
   
    
    
    router,
    store,
    render: h => h(App)
}).$mount('#app')

// 路由跳转之前拦截,不能在购物车为空的情况下进入购物车页面
router.beforeEach((to, from, next) => {
   
    
    
    if( to.path === '/') {
   
    
    
        next()
    } else {
   
    
    
        let carList = JSON.parse(localStorage.getItem('car'))
        if (carList.length > 0) {
   
    
    
            next()
        } else {
   
    
    
            Message({
   
    
    
                message: "购物车空空如也,赶紧去添加吧!",
                type: 'error'
            })
            next('/')
        }
    }
})

(2) Router.js

import Vue from 'vue'
import Router from 'vue-router'
import List from '@/views/List.vue'

Vue.use(Router)

export default new Router({
   
    
    
    routes: [
        // List页面
        {
   
    
    
            path: '/',
            component: List
        },
        // 购物车页面
        {
   
    
    
            path: '/home',
            name: 'home',
            // 异步引入
            component: () => import('@/views/Home')
        },
    ]
})

(3)store.js

Note: store.js here is a relatively complex page in this project, mainly because there are many synchronization messages and variables in it.

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
   
    
    
    state: {
   
    
    
        // 购物车 本地存储,防止数据丢失
        car: localStorage["car"] ? JSON.parse(localStorage["car"]) : [],
        // 总价
        totlePrice: 0,
        // 全选状态
        all_selected: false,
        // 购物车中购买的数量
        payNum: 0,
        // list页面控制‘加入购物车按钮’的样式  本地存储,防止数据丢失
        isShow: localStorage["isShow"] ? JSON.parse(localStorage["isShow"]) : []
    },
    getters: {
   
    
    
        // 时时监听car的变化
        carList(state) {
   
    
    
            // 初始化全选状态
            if (state.all_selected) {
   
    
    
                state.car.forEach(item => item.isBuy = true)
            }
            return state.car;
        },
        // 购买的总价钱
        allPrice(state) {
   
    
    
            let totlePrice = 0
            state.car.forEach(item => {
   
    
    
                // 如果加入购物车后点击了购买按钮
                if (item.isBuy) {
   
    
    
                    totlePrice += item.num * item.price
                }
            })
            return state.totlePrice = totlePrice
        },
        // 购买的商品的总数量
        payLength(state) {
   
    
    
            let paylength = 0
            state.car.forEach(item => {
   
    
    
                if (item.isBuy) {
   
    
    
                    paylength += item.num
                }
            })
            return  state.payNum = paylength;
        }
    },
    // 同步消息
    mutations: {
   
    
    
        // 从购物车中删除该商品
        deleteProduct(state, id) {
   
    
    
            // 商品在购物车中索引值
            let index = state.car.findIndex(item => item._id === id)
            // 商品在isShow中的索引值
            let indexShow = state.isShow.findIndex(item =>item.id === id)
            // 将购物车中该商品的selected属性改成false
            state.car[index].selected = false;
            // 从购物车中删除该商品
            state.car.splice(index, 1)

Guess you like

Origin blog.csdn.net/wh13821662259/article/details/109122755