vue实现前台显示
Vue 实现前台显示的核心方法
基础项目搭建
使用 Vue CLI 或 Vite 创建项目,安装必要依赖:
npm create vue@latest
选择需要的配置(Router/Pinia/ESLint等),完成后进入开发模式:
npm run dev
组件化开发
创建可复用的.vue单文件组件,包含模板、脚本和样式:
<template>
<div class="product-card">
<h3>{{ product.name }}</h3>
<img :src="product.image" :alt="product.name">
<p>价格: {{ product.price }}</p>
</div>
</template>
<script setup>
defineProps({
product: Object
})
</script>
<style scoped>
.product-card {
border: 1px solid #ddd;
padding: 1rem;
}
</style>
状态管理
使用Pinia或Vuex管理全局状态(以Pinia为例):
// stores/counter.js
import { defineStore } from 'pinia'
export const useProductStore = defineStore('product', {
state: () => ({
items: []
}),
actions: {
async fetchProducts() {
this.items = await api.getProducts()
}
}
})
路由配置
通过Vue Router实现页面导航:
// router/index.js
import { createRouter } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const routes = [
{
path: '/',
component: HomeView
},
{
path: '/product/:id',
component: () => import('../views/ProductDetail.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
数据绑定
使用响应式API处理动态内容:
<script setup>
import { ref, computed } from 'vue'
const searchQuery = ref('')
const products = ref([])
const filteredProducts = computed(() => {
return products.value.filter(p =>
p.name.includes(searchQuery.value)
)
})
</script>
UI库集成
引入Element Plus等UI框架快速构建界面:
// main.js
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
app.use(ElementPlus)
API交互
使用axios进行数据请求:
import axios from 'axios'
const fetchData = async () => {
try {
const res = await axios.get('/api/products')
products.value = res.data
} catch (err) {
console.error(err)
}
}
动态样式处理
结合CSS变量实现主题切换:
<template>
<div :style="{'--primary-color': themeColor}">
<!-- 内容 -->
</div>
</template>
<style>
.button {
background-color: var(--primary-color);
}
</style>
性能优化
使用懒加载和代码分割:
const ProductDetail = () => import('./views/ProductDetail.vue')
部署准备
配置生产环境构建:
npm run build
生成的dist目录可直接部署到Web服务器。







