vue实现的页面
以下是基于 Vue.js 实现页面的核心方法和实践要点:
项目初始化与配置
使用 Vue CLI 或 Vite 创建项目:
npm create vue@latest # Vue CLI
npm create vite@latest # Vite
配置 vue.config.js 可自定义 Webpack 或修改 Vite 的构建选项。
组件化开发
单文件组件(SFC)结构示例:

<template>
<div class="container">
<h1>{{ title }}</h1>
<ChildComponent :data="items" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: { ChildComponent },
data() {
return {
title: 'Vue Page',
items: ['Item 1', 'Item 2']
}
}
}
</script>
<style scoped>
.container {
max-width: 1200px;
}
</style>
状态管理
对于复杂状态管理,推荐 Pinia:
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++
}
}
})
路由配置
Vue Router 的基本配置:
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/',
component: () => import('./views/Home.vue')
},
{
path: '/about',
component: () => import('./views/About.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
生命周期管理
组合式 API 的生命周期用法:

<script setup>
import { onMounted, ref } from 'vue'
const data = ref(null)
onMounted(async () => {
const res = await fetch('/api/data')
data.value = await res.json()
})
</script>
响应式数据处理
使用 ref 和 reactive:
const count = ref(0)
const state = reactive({
user: null,
loading: false
})
watchEffect(() => {
console.log('Count changed:', count.value)
})
性能优化
- 使用
v-once静态内容缓存 - 路由懒加载组件
- 虚拟滚动 (
vue-virtual-scroller) 处理长列表 - 使用
keep-alive缓存组件状态
测试方案
Vitest 单元测试示例:
import { mount } from '@vue/test-utils'
import Component from './Component.vue'
test('renders message', () => {
const wrapper = mount(Component, {
props: { msg: 'Hello' }
})
expect(wrapper.text()).toContain('Hello')
})
部署构建
生产环境构建命令:
npm run build # 生成 dist 目录
可通过 nginx 或云服务部署静态资源,或使用 SSR 方案如 Nuxt.js。






