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.
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
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>{{ 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.
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.
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:
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.
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" :src="product.image" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ 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.
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 :src="product.image" class="img-fluid" alt=""> </div> <div class="col-md-6"> <h2>{{ 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 } ] })
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 class="modal-title">购物车</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.
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>确认订单</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>订单详情</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!