Double 11 has just passed you are not ready to start the double 12? 🤔 when it comes to shopping, shopping cart is indispensable. How can shopping cart function be realized? With respect to millet mall shopping cart, let’s talk about it

Here’s how it looks (basically like the shopping cart we’ve seen before):

Think before you act

1. The database needs to build two tables: All commodity tables (CART) and cart commodity tables (CartSelected)

2. The cart table: id (primary key, since the increase), img, title, price, how many

Cartselected table: id (linked to cart table id), img, title, price, how many, num, checked (if selected, only two values 0 and 1)

3. The axios request is carried out in actions, the requested data is put into state, and the relevant calculation is carried out in getters

4. Axios needs to be used multiple times and can be wrapped

5. The commodity bar displays the CART table data, and the shopping cart bar displays the CARTSelected table data

The preparation of the instruments

  • vscode
  • navicat
  • mysql

Realize the function

1. Set up background services and connect to mysql

Const config = {database: {DATEBASE: 'xiaomi', USERNAME: 'root', PASSWORD: '******', PORT: '3306', HOST: 'localhost'}} var pool = mysql.createpool ({host: config.database. host, user: config.database.USERNAME, password: config.database.PASSWORD, database: config.database.DATEBASE, port: Config.database.port}) // let allServies = {query: function (sql, values) { return new Promise((resolve, reject) => { pool.getConnection(function (err, connection) { if (err) { reject(err) } else { connection.query(sql, values, (err, Rows) => {if (err) {reject(err)} else {resolve(rows)} Connection.release () // Release connection pool})}})})}}Copy the code

If the connection is successful, you can use Postman or test it directly in the browser (not here).

2. Detail each function implementation (follow SQL statement -> back-end interface -> VUex -> Specific Component)

  • Random query
  • Scenario: The page displays 20 items when the cart is empty, and 10 items when the cart has items

    Let findallgoods = function (num) {let _sql = 'select * from cart order by rand() limit ${num}; ` return allServies.query(_sql) }Copy the code

    Back-end routing:

    router.post('/allcart', async (ctx, next) => {
      let _num = ctx.request.body.num
      await userService.findallgoods(_num).then((res) => {
        ctx.body = {
          data: res
        }
      })
    })
    Copy the code

    Front end access

    data () {
        return{requestGoods (nums)}}, methods: {requestGoods (nums) {'http://localhost:3000/users/allcart',
          method: 'post', data: { num: nums } }).then(res => { this.allcart = res.data.data }).catch(err => { console.log(err) }) } }, watch: Cart (newval, old) {// Monitor the size of the cart to determine how many items (10 or 20) are requested.if(newval.length == 0 && old.length ! = 0) { this.requestGoods(20) }else {
            this.requestGoods(10)
          }
        }
      },
    Copy the code

  • Add to cart and remove from cart
  • Let findcart = function (id) {let _sql = 'select * from CARTselected WHERE id="${id}"; 'return allServies. Query (_sql)} // Let findallcart = function () {let _sql =' select * from cartselected; 'return allServies. Query (_sql)} // Insert cart (id, title, price, recommend, img, num, checked) let insertgoods = function (value) { let _sql = `insert into cartselected set id=? ,title=? ,price=? ,recommend=? ,img=? ,num=? ,checked=? ` return allServies.query(_sql, Function (value) {let _sql = 'delete from cartselected WHERE id=? ` return allServies.query(_sql, value) }Copy the code
    Router. Post ('/allcarts', async (CTX, next) => { await userService.findallcart().then((res) => { ctx.body = { data: Router. Post ('/insertcart', async (CTX, next) => { let _id = ctx.request.body.id let _title = ctx.request.body.title let _price = ctx.request.body.price let _recommend = ctx.request.body.recommend let _img = ctx.request.body.img let _num = ctx.request.body.num let _checked = ctx.request.body.checked if (! _id) { return } else { let cart = { id: _id, title: _title, price: _price, recommend: _recommend, img: _img, num: _num, checked: _checked} await userservice.findCart (cart.id).then(async (res) => {if (res.length) {try {throw Error(' already in cart ')} catch (error) { console.log(error) } ctx.body = { code: '800003', data: 'err', mess: }} else {await userservice.insertGoods ([cart.id, cart.title, cart.price, cart.recommend, cart.img, cart.num, cart.checked]).then(async (res) => { let r = '' if (res.affectedRows ! == 0) { await userService.findcartgoods(cart.id).then((res1) => { ctx.body = { code: '800000', data: res1, mess: Else {r = 'error' ctx.body = {code: '800004', data: r, mess: Router. Post ('/ deleteGood ', async (CTX, async (CTX, async)) next) => { let _id = ctx.request.body.id await userService.deletegoods(_id).then(res => { ctx.body = { code: '800000', data: res, mess: 'delete succeeded'}}). Catch (err => {ctx.body = {code: '800002', data: err}})})Copy the code

    Vuex actions:

    Getcart ({commit}, status) {// Get the cart table data axios({url:'http://localhost:3000/users/allcarts',
          method: 'post',
          data: {}
        }).then(res => {
          commit('setcart', res.data. Data) }). Catch (err => {console.log(err)})}, addcart ({id, title, price, recommend, img, num, Checked}) {// Add to cart axios({url:'http://localhost:3000/users/insertcart',
          method: 'post',
          data: {
            id: id,
            title: title,
            price: price,
            recommend: recommend,
            img: img,
            num: num,
            checked: checked
          }
        }).then(res => {
          if (res.data.code === '800000') {
            dispatch('getcart'); // Request shopping cart data again}else {
            console.log('Failed to add shopping cart'}}). Catch (err => {console.log(err)})}, deletecart ({dispatch}, id) {// Delete an item from the shopping cart axios({url:'http://localhost:3000/users/deletegood',
          method: 'post',
          data: {
            id: id
          }
        }).then (res => {
          dispatch('getcart')})}Copy the code

    Component:

    Addcart (id, title, price, recommend, img, num, checked) {// click addcart.$store.dispatch('addcart', {id, title, price, recommend, img, num, checked})}, deletecart (id) {$store.dispatch('deletecart', id)
        }
    Copy the code

  • Increase or decrease quantity
  • // Increase the number of shopping carts let _sql = 'update cartselected set num=num+1 where id="${id}"'// shopping cart quantity reduced let _sql ='update cartselected set num=num- 1 where id="${id}" and num> =2'// num > 2 because the number cannot be reduced to 0Copy the code

    The backend interface

    Router. post('/ addCartnum ', async (CTX, next) => {}) router.post('/reducecartnum', async (ctx, next) => {})Copy the code

    vuex:

    Addcartnum ({dispatch}, params) {}) // Increase the number reducecartnum ({dispatch}, params) {}) // reduce the numberCopy the code

    Component:

    Add (id) {// Increase the number of items this.$store.dispatch('addcartnum', id)}, reduce (id) {// Reduce the quantity of goods this.$store.dispatch('reducecartnum', id)
        }
    Copy the code

  • Select all and single
  • Let allFalse = function () {let _sql = 'update cartselected set checked=0' return allServies. Query (_sql) Let allTrue = function () {let _sql = 'update cartselected set checked=1' return allServies. Query (_sql)} // Let singlesELECT = function (id) {let _sql = 'update cartselected set checked=(case when checked=0) then 1 else checked=0 end) where id="${id}"` return allServies.query(_sql) }Copy the code

    Back-end interface:

    Router. post('/ allTrue ', async (CTX, next) => {}) Post ('/ singlesELECT ', async (CTX, next) => {})Copy the code

    vuex:

    allfalse ({dispatch}, status) {})
    alltrue ({dispatch}, status) {})
    singleselect ({dispatch}, status) {})
    Copy the code

    component

    data () {
        return {
            allcheked: false}}, methods: {allselect() {// Select allif (this.allcheked) {
           this.$store.dispatch('allfalse')}else {
           this.$store.dispatch('alltrue'}}, singleselected (id) {// Select this.$store.dispatch('singleselect', id) } }, computed: { ... mapGetters(['cart'
        ])
    },
    watch: {
        cart: {
          handler(newValue, oldValue) {
            for (let i = 0; i < newValue.length; i++) {
              console.log(newValue[i].checked)
              if (newValue[i].checked == 0) {
                this.allcheked = false
                return 
              }
              this.allcheked = true
            }
          },
          deep: true}}Copy the code

  • The relevant calculation
  • getters

    Const getters = {cart: state => state. Cart, littletotalPrice (state)let money = []
        if(state.cart.length ! = 0) { state.cart.forEach((item) => { console.log(item)let price = item.price.substring(0, item.price.indexOf('å…ƒ'))
             money.push(price * item.num)
          })
          return money
        } else {
          return[]}}, totalPrice (state) {// Totallet selected = state.cart.filter(function(elem) {
          return elem.checked == 1
        })
        let totalprice = 0
        for (let i = 0; i < selected.length; i++) {
          let price1 = selected[i].price.substring(0, selected[i].price.indexOf('å…ƒ'))
          let price2 = price1 * selected[i].num
          totalprice += price2
        }
        returnTotalprice}, selectedNum (state) {// The number of selectedlet selected = state.cart.filter(function(elem) {
          return elem.checked == 1
        })
        returnSelect. Length}, totalNum (state) {// Selectlet sum = 0
        for (let i = 0; i < state.cart.length; i++) {
          sum = sum + state.cart[i].num
        }
        return sum
      }
    }
    Copy the code

    conclusion

    Each method has to request the back-end interface once or even more times, causing great pressure on the back-end. Because the operation of data is mostly driven by SQL statements, it is not very friendly for students who are not skilled in SQL statements, so better methods are needed to solve it.

    subsequent

    Next time we will improve the implementation of our shopping cart functionality, interface value access once, all functions implemented in VUex