Table of Contents
1. Basic knowledge of Vue
1.1 Installation and use of Vue
1.2 Component-based development of Vue
{{ title }}
1.3 Vue’s event binding and triggering
2. Design of e-commerce platform
3. Implementation steps of e-commerce platform
3.1 Homepage
{{ product.name }}
3.2 Product details page
3.3 Shopping cart page
购物车
3.4 Order confirmation page and order success page
确认订单
订单详情
Home Web Front-end Vue.js Vue development practice: building a responsive e-commerce platform

Vue development practice: building a responsive e-commerce platform

Nov 03, 2023 am 08:22 AM
vue Responsive Electronic business platform

Vue development practice: building a responsive e-commerce platform

Vue is a popular JavaScript framework that is widely used in web development. This article will introduce how to use Vue to build a responsive e-commerce platform. We will use Vue to build the front-end interface and call the back-end API interface to obtain data. We will also use Vue's responsive mechanism to achieve automatic updating and dynamic rendering of data. The following will introduce the basic knowledge of Vue, the design and implementation steps of the e-commerce platform.

1. Basic knowledge of Vue

1.1 Installation and use of Vue

Vue can be used through CDN reference or directly downloading the installation package. We use the officially provided Vue CLI build tool here to quickly build a Vue project.

Install Vue CLI globally:

npm install -g vue-cli
Copy after login

Create a new Vue project using Vue CLI:

vue create my-project
Copy after login

1.2 Component-based development of Vue

The core of Vue The idea is component development, and a Vue application can be composed of multiple components. Each component can contain templates, business logic and styles. Components can nest within each other and pass data around, forming complex page structures.

The following is a simple Vue component example:

<template>
  <div>
    <h1 id="title">{{ title }}</h1>
    <ul>
      <li v-for="item in items">{{ item }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'MyComponent',
  props: {
    title: String,
    items: Array
  }
}
</script>

<style>
h1 {
  color: #333;
}
li {
  color: #666;
}
</style>
Copy after login

The above code defines a component named MyComponent, which contains a title and a list. Components can pass parent component data through the props attribute. Here, the title and items attributes are used.

1.3 Vue’s event binding and triggering

Vue’s event binding and triggering are similar to other frameworks. You can bind events through the v-on directive and trigger events through the $emit method. Events can pass parameters and data.

The following is a simple event binding and triggering example:

<template>
  <div>
    <button v-on:click="handleClick">Click me</button>
  </div>
</template>

<script>
export default {
  methods: {
    handleClick() {
      this.$emit('custom-event', 'Hello, world!')
    }
  }
}
</script>
Copy after login

The above code defines a method named handleClick, which will trigger the custom-event event and pass a character when the button is clicked. String parameters.

2. Design of e-commerce platform

E-commerce platforms usually include functions such as product display, shopping cart, order confirmation and payment. We design a simple e-commerce platform based on these functions, including the following pages:

  • Home page: displays all product information and supports search and classification.
  • Product details page: Displays detailed information of a single product and supports adding to the shopping cart.
  • Shopping cart page: Displays all product information added to the shopping cart and supports clearing and settlement operations.
  • Order confirmation page: Displays all selected product information and supports filling in information such as address and payment method.
  • Order success page: displays order details and supports returning to the home page.

For the convenience of demonstration, we only provide static data and API interfaces simulated with axios. The back-end data uses JSON format and contains all product information and order information.

3. Implementation steps of e-commerce platform

3.1 Homepage

The homepage displays all product information and supports search and classification. We use Bootstrap and FontAwesome libraries to beautify page styles and icons.

First install these two libraries:

npm install bootstrap font-awesome --save
Copy after login

Add style references to the App.vue file:

<template>
  <div>
    <nav class="navbar navbar-dark bg-dark">
      <a class="navbar-brand" href="#">电商平台</a>
    </nav>
    <div class="container mt-4">
      <router-view></router-view>
    </div>
  </div>
</template>

<style>
@import "bootstrap/dist/css/bootstrap.min.css";
@import "font-awesome/css/font-awesome.min.css";
</style>
Copy after login

Use Vue Router to implement page jumps and pass parameters. Add the following code to the main.js file:

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')
Copy after login

Create a router.js file to define routing configuration:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './views/Home.vue'

Vue.use(VueRouter)

export default new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    }
  ]
})
Copy after login

Create a Home.vue file to implement homepage display and search functions:

<template>
  <div>
    <div class="input-group mb-4">
      <input type="text" class="form-control" v-model="searchText" placeholder="Search...">
      <div class="input-group-append">
        <button class="btn btn-outline-secondary" type="button" v-on:click="search">Search</button>
      </div>
    </div>
    <div class="row">
      <div class="col-md-4 mb-4" v-for="product in products" :key="product.id">
        <div class="card">
          <img class="card-img-top lazy"  src="/static/imghw/default1.png"  data-src="product.image"  : alt="Card image cap">
          <div class="card-body">
            <h5 id="product-name">{{ product.name }}</h5>
            <p class="card-text">{{ product.description }}</p>
            <p class="card-text font-weight-bold text-danger">{{ product.price }}</p>
            <button class="btn btn-primary" v-on:click="addToCart(product)">加入购物车</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      products: [],
      searchText: ''
    }
  },
  created() {
    this.getProducts()
  },
  methods: {
    getProducts() {
      axios.get('/api/products').then(response => {
        this.products = response.data
      })
    },
    search() {
      axios.get('/api/products', {
        params: {
          search: this.searchText
        }
      }).then(response => {
        this.products = response.data
      })
    },
    addToCart(product) {
      this.$emit('add-to-cart', product)
    }
  }
}
</script>
Copy after login

The above code calls the API interface through axios to obtain product information, and supports search and add to shopping cart operations.

3.2 Product details page

The product details page displays the detailed information of a single product and supports adding to the shopping cart. We use Vue Router to pass the product ID parameter.

Create the Product.vue file to implement the product details page:

<template>
  <div>
    <div class="row mt-4">
      <div class="col-md-6">
        <img class="img-fluid lazy"  src="/static/imghw/default1.png"  data-src="product.image"  : alt="">
      </div>
      <div class="col-md-6">
        <h2 id="product-name">{{ product.name }}</h2>
        <p>{{ product.description }}</p>
        <p class="font-weight-bold text-danger">{{ product.price }}</p>
        <button class="btn btn-primary btn-lg" v-on:click="addToCart(product)">加入购物车</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      product: {}
    }
  },
  created() {
    const productId = this.$route.params.id
    axios.get(`/api/products/${productId}`).then(response => {
      this.product = response.data
    })
  },
  methods: {
    addToCart(product) {
      this.$emit('add-to-cart', product)
    }
  }
}
</script>
Copy after login

Use Vue Router to pass the product ID parameter. Modify the router.js configuration file:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './views/Home.vue'
import Product from './views/Product.vue'

Vue.use(VueRouter)

export default new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/product/:id',
      name: 'product',
      component: Product
    }
  ]
})
Copy after login

3.3 Shopping cart page

The shopping cart page displays all product information added to the shopping cart and supports clearing and settlement operations. We use Vuex for state management and data sharing.

Install the Vuex library:

npm install vuex --save
Copy after login

Create the store.js file to configure the state management of Vuex:

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cart: []
  },
  mutations: {
    addToCart(state, product) {
      const item = state.cart.find(item => item.id === product.id)
      if (item) {
        item.quantity++
      } else {
        state.cart.push({
          ...product,
          quantity: 1
        })
      }
    },
    removeFromCart(state, productId) {
      state.cart = state.cart.filter(item => item.id !== productId)
    },
    clearCart(state) {
      state.cart = []
    }
  },
  getters: {
    cartTotal(state) {
      return state.cart.reduce((total, item) => {
        return total + item.quantity
      }, 0)
    },
    cartSubtotal(state) {
      return state.cart.reduce((total, item) => {
        return total + item.price * item.quantity
      }, 0)
    }
  }
})
Copy after login

Modify the code of App.vue to configure the state management of Vuex:

<template>
  <div>
    <nav class="navbar navbar-dark bg-dark">
      <a class="navbar-brand" href="#">电商平台</a>
      <span class="badge badge-pill badge-primary">{{ cartTotal }}</span>
    </nav>
    <div class="container mt-4">
      <router-view :cart="cart" v-on:add-to-cart="addToCart"></router-view>
    </div>
    <div class="modal" tabindex="-1" role="dialog" v-if="cart.length > 0">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 id="购物车">购物车</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <table class="table">
              <thead>
                <tr>
                  <th>名称</th>
                  <th>单价</th>
                  <th>数量</th>
                  <th>小计</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in cart" :key="item.id">
                  <td>{{ item.name }}</td>
                  <td>{{ item.price }}</td>
                  <td>
                    <button class="btn btn-sm btn-danger" v-on:click="removeFromCart(item.id)">-</button>
                    {{ item.quantity }}
                    <button class="btn btn-sm btn-success" v-on:click="addToCart(item)">+</button>
                  </td>
                  <td>{{ item.price * item.quantity }}</td>
                  <td><i class="fa fa-remove text-danger" v-on:click="removeFromCart(item.id)"></i></td>
                </tr>
              </tbody>
              <tfoot>
                <tr>
                  <td colspan="2">共 {{ cartTotal }} 件商品</td>
                  <td colspan="2">总计 {{ cartSubtotal }}</td>
                  <td><button class="btn btn-sm btn-danger" v-on:click="clearCart()">清空购物车</button></td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import store from './store'

export default {
  computed: {
    cart() {
      return store.state.cart
    },
    cartTotal() {
      return store.getters.cartTotal
    }
  },
  methods: {
    addToCart(product) {
      store.commit('addToCart', product)
    },
    removeFromCart(productId) {
      store.commit('removeFromCart', productId)
    },
    clearCart() {
      store.commit('clearCart')
    }
  }
}
</script>
Copy after login

The above code uses Vuex to implement the functions of adding, deleting, clearing and calculating the shopping cart.

3.4 Order confirmation page and order success page

The order confirmation page displays all selected product information and supports filling in information such as address and payment method. The order success page displays the order details and supports returning to the home page. We use Vue Router to pass order information parameters.

Create the Cart.vue file to implement the order confirmation page:

<template>
  <div>
    <h2 id="确认订单">确认订单</h2>
    <table class="table">
      <thead>
        <tr>
          <th>名称</th>
          <th>单价</th>
          <th>数量</th>
          <th>小计</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in cart" :key="item.id">
          <td>{{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>{{ item.quantity }}</td>
          <td>{{ item.price * item.quantity }}</td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="2">共 {{ cartTotal }} 件商品</td>
          <td colspan="2">总计 {{ cartSubtotal }}</td>
        </tr>
      </tfoot>
    </table>
    <div class="form-group">
      <label for="name">姓名</label>
      <input type="text" class="form-control" id="name" v-model="name">
    </div>
    <div class="form-group">
      <label for="address">地址</label>
      <textarea class="form-control" id="address" v-model="address"></textarea>
    </div>
    <div class="form-group">
      <label for="payment">支付方式</label>
      <select class="form-control" id="payment" v-model="payment">
        <option value="alipay">支付宝</option>
        <option value="wechatpay">微信支付</option>
        <option value="creditcard">信用卡</option>
      </select>
    </div>
    <button class="btn btn-primary btn-lg" v-on:click="checkout">提交订单</button>
  </div>
</template>

<script>
export default {
  props: ['cartTotal', 'cartSubtotal'],
  data() {
    return {
      name: '',
      address: '',
      payment: 'alipay'
    }
  },
  methods: {
    checkout() {
      this.$router.push({
        name: 'order-success',
        params: {
          name: this.name,
          address: this.address,
          payment: this.payment,
          cart: this.$props.cart,
          cartTotal: this.cartTotal,
          cartSubtotal: this.cartSubtotal
        }
      })
    }
  }
}
</script>
Copy after login

Create the OrderSuccess.vue file to implement the order success page:

<template>
  <div>
    <h2 id="订单详情">订单详情</h2>
    <p>姓名:{{ name }}</p>
    <p>地址:{{ address }}</p>
    <p>支付方式:{{ payment }}</p>
    <table class="table">
      <thead>
        <tr>
          <th>名称</th>
          <th>单价</th>
          <th>数量</th>
          <th>小计</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in cart" :key="item.id">
          <td>{{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>{{ item.quantity }}</td>
          <td>{{ item.price * item.quantity }}</td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="2">共 {{ cartTotal }} 件商品</td>
          <td colspan="2">总计 {{ cartSubtotal }}</td>
        </tr>
      </tfoot>
    </table>
    <button class="btn btn-primary btn-lg" v-on:click="backHome">返回首页</button>
  </div>
</template>

<script>
export default {
  props: ['name', 'address', 'payment', 'cart', 'cartTotal', 'cartSubtotal'],
  methods: {
    backHome() {
      this.$router.push('/')
    }
  }
}
</script>
Copy after login

Use Vue Router to pass the order information parameters. Modify the configuration file of router.js:

import Vue from 'vue'
Copy after login

The above is the detailed content of Vue development practice: building a responsive e-commerce platform. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1254
29
C# Tutorial
1228
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

See all articles