Vue.js Shopping Cart with Drag and Drop

HTMLHTMLBeginner
Practice Now

Introduction

In this project, you will learn how to implement an online shopping cart with drag and drop functionality. This project aims to help you understand and apply the concepts of Vue.js and the drag and drop APIs provided by web browsers.

👀 Preview

finished

🎯 Tasks

In this project, you will learn:

  • How to set up the project and familiarize yourself with the provided files and structure.
  • How to implement the drag and drop functionality for the online shopping cart, allowing users to add products to the cart.
  • How to display the shopping cart information, including the number of products, the product details, and the total price.
  • How to test the online shopping cart and ensure the functionality works as expected.

🏆 Achievements

After completing this project, you will be able to:

  • Use Vue.js to build a web application.
  • Implement drag and drop functionality using the web browser's built-in APIs.
  • Display dynamic data and update the user interface based on user interactions.
  • Write clean and maintainable code by organizing your application into components.

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL html(("`HTML`")) -.-> html/BasicStructureGroup(["`Basic Structure`"]) javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) html/BasicStructureGroup -.-> html/basic_elems("`Basic Elements`") html/BasicStructureGroup -.-> html/viewport("`Viewport Declaration`") javascript/BasicConceptsGroup -.-> javascript/functions("`Functions`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/es6("`ES6 Features`") subgraph Lab Skills html/basic_elems -.-> lab-299911{{"`Vue.js Shopping Cart with Drag and Drop`"}} html/viewport -.-> lab-299911{{"`Vue.js Shopping Cart with Drag and Drop`"}} javascript/functions -.-> lab-299911{{"`Vue.js Shopping Cart with Drag and Drop`"}} javascript/array_methods -.-> lab-299911{{"`Vue.js Shopping Cart with Drag and Drop`"}} javascript/es6 -.-> lab-299911{{"`Vue.js Shopping Cart with Drag and Drop`"}} end

Set Up the Project Structure

In this step, you will set up the project files and structure. Follow the steps below to complete this step:

Open the project folder. The directory structure is as follows:

├── images
│   ├── book.jpeg
│   ├── box.jpeg
│   ├── paper.jpeg
│   ├── trolley.jpeg
│   └── tv.jpg
├── index.css
├── index.html
├── js
│   ├── http-vue-loader.js
│   └── vue.min.js
└── trolley.vue

Among them:

  • The images folder provides the product images required by the page.
  • index.css is the style file.
  • index.html is the main page.
  • js/vue.min.js and js/http-vue-loader.js are files related to the Vue library.
  • trolley.vue is the component file that needs to be completed.

Click on Go Live button in the bottom right corner of WebIDE, to run the project.

Next, open "Web 8080" on the top of the VM and refresh it manually and you will see the page.

Implement the Drag and Drop Functionality

In this step, you will implement the drag and drop functionality for the online shopping cart.

  1. Open the trolley.vue file.
  2. In the data() function, you can see the goods array, which contains the product information. This data will be used to display the products in the "Good List" section.
  3. Add the following code in the methods section:
methods: {
  dragstart(e, good) {
    e.dataTransfer.setData("name", good.name);
    e.dataTransfer.setData("price", good.price);
  },
  dragover(e) {
    e.preventDefault();
  },
  drop(e) {
    const { bought } = this;
    const name = e.dataTransfer.getData("name");
    const price = e.dataTransfer.getData("price");
    bought.push({ name, price: Number(price) });
  }
}

Explanation:

  • The dragstart method is called when the user starts dragging a product. It sets the product name and price in the dataTransfer object, which can be accessed later in the drop method.
  • The dragover method is called when the dragged item is over the shopping cart. It prevents the default behavior of the browser, which is necessary for the drop event to work.
  • The drop method is called when the user drops the dragged item into the shopping cart. It retrieves the product name and price from the dataTransfer object and adds the product to the bought array.
  1. In the computed section, add the following code:
computed: {
  totalPrice() {
    const { bought } = this;
    var sum = 0;
    for (key in bought) {
      sum += bought[key].price;
    }
    return sum;
  },
  goodsDetail() {
    const { bought } = this;
    const names = [];
    const goods = [];
    for (key in bought) {
      names.push(bought[key].name);
    }
    function getRepeatNum() {
      return names.reduce(function (prev, next) {
        prev[next] = prev[next] + 1 || 1;
        return prev;
      }, {});
    }
    for (key in getRepeatNum()) {
      goods.push(`${key}*${getRepeatNum()[key]}`);
    }
    return goods.join(" ");
  }
},

Explanation:

  • The totalPrice computed property calculates the total price of the products in the shopping cart.
  • The goodsDetail computed property generates the details of the products in the shopping cart, displaying the product name and quantity.

Binding Drag and Drop Events to HTML

In this step, we need to bind the drag and drop event to the div tag.

  1. In the template section of the trolley.vue file, locate the <div class="good-list"> element.
  2. In the <div class="good-list"> element change to the following code:
<div class="good-list">
  <div
    v-for="good in goods"
    :key="good.name"
    class="good"
    draggable="true"
    @dragstart="dragstart($event, good)"
  >
    <img :src="good.cover" draggable="false" />
    <span>{{ good.name }}</span>
    <span>$ {{ good.price }}</span>
  </div>
</div>
  1. Locate the <div class="trolley" id="trolley"> element.
  2. Change the <div class="trolley" id="trolley"> element to the following code:
<div id="trolley" class="trolley" @dragover="dragover" @drop="drop">
  <span id="bought" class="bought" v-if="bought.length !== 0"
    >{{ bought.length }}</span
  >
  <img src="./images/trolley.jpeg" />
</div>

Test the Online Shopping Cart

  1. Save the trolley.vue file.
  2. Refresh the page to see the initial state of the online shopping cart.
  3. Try dragging and dropping the product images into the shopping cart.
  4. Observe the changes in the shopping cart, including the number of products, the product details, and the total price.
  5. Ensure that the functionality works as expected.

The final implementation effect is as follows:

Image Description

Congratulations! You have successfully implemented the online shopping cart using the provided base project and the drag and drop functionality.

✨ Check Solution and Practice

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other HTML Tutorials you may like