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
Create a new Vue project using Vue CLI:
vue create my-project
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>
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>
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
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>
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')
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 } ] })
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/imghwm/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>
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/imghwm/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>
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 } ] })
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
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) } } })
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">×</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>
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>
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>
Use Vue Router to pass the order information parameters. Modify the configuration file of router.js:
import Vue from 'vue'
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!

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version
SublimeText3 Linux latest version
