vue前端实现
Vue 前端实现方法
环境搭建与项目初始化
使用 Vue CLI 或 Vite 创建项目,推荐 Node.js 版本 ≥16.0.0。通过以下命令初始化:
npm init vue@latest # Vue CLI
npm create vite@latest # Vite
安装核心依赖:
npm install vue vue-router pinia axios
组件化开发
单文件组件(SFC)结构示例:
<template>
<div class="component">
<button @click="handleClick">{{ buttonText }}</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const buttonText = ref('Click me')
const handleClick = () => {
buttonText.value = 'Clicked!'
}
</script>
<style scoped>
.component {
margin: 1rem;
}
</style>
状态管理
Pinia 状态管理示例:
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++
}
}
})
组件中使用:
<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
</script>
<template>
<button @click="counter.increment">{{ counter.count }}</button>
</template>
路由配置
Vue Router 基础配置:

import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({
history: createWebHistory(),
routes
})
API 交互
Axios 封装示例:
// api/index.js
import axios from 'axios'
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000
})
export const getData = (params) => instance.get('/data', { params })
响应式设计
组合式 API 响应式处理:
import { reactive, computed } from 'vue'
const state = reactive({
items: [],
filter: ''
})
const filteredItems = computed(() => {
return state.items.filter(item =>
item.name.includes(state.filter)
)
})
性能优化
懒加载组件:

const LazyComponent = defineAsyncComponent(() =>
import('./LazyComponent.vue')
)
路由懒加载:
const routes = [
{
path: '/heavy',
component: () => import('./HeavyPage.vue')
}
]
测试方案
单元测试示例(Vitest):
import { test, expect } from 'vitest'
import { shallowMount } from '@vue/test-utils'
import MyComponent from './MyComponent.vue'
test('renders button', () => {
const wrapper = shallowMount(MyComponent)
expect(wrapper.find('button').exists()).toBe(true)
})
部署配置
Vite 生产构建:
npm run build
Docker 部署示例:
FROM node:16 as builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html






