用vue实现的页面
使用 Vue.js 实现页面需要结合其核心特性(如组件化、响应式数据绑定)和生态工具(如 Vue Router、Pinia)。以下是一个清晰的实现流程和关键代码示例:
初始化项目
通过 Vue CLI 或 Vite 创建项目:
npm create vue@latest my-project
选择需要的配置(如 Router、Pinia、ESLint)。
页面结构设计
在 src/views/ 目录下创建页面组件(例如 HomeView.vue):
<template>
<div class="home">
<h1>{{ pageTitle }}</h1>
<CustomButton @click="handleClick" />
</div>
</template>
<script setup>
import { ref } from 'vue';
import CustomButton from '@/components/CustomButton.vue';
const pageTitle = ref('Home Page');
const handleClick = () => {
console.log('Button clicked');
};
</script>
<style scoped>
.home {
padding: 20px;
}
</style>
路由配置
在 src/router/index.js 中定义路由:
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '@/views/HomeView.vue';
const routes = [
{
path: '/',
name: 'home',
component: HomeView
}
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
状态管理(可选)
使用 Pinia 管理全局状态。创建 src/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>
组件通信
父子组件通过 props 和 emit 交互:
<!-- 子组件 -->
<template>
<button @click="$emit('custom-event')">Click Me</button>
</template>
<!-- 父组件 -->
<ChildComponent @custom-event="handleEvent" />
响应式数据处理
使用 ref 或 reactive 管理数据:

const userData = reactive({
name: 'Alice',
age: 25
});
watchEffect(() => {
console.log('User age changed:', userData.age);
});
生命周期钩子
常用钩子如 onMounted:
import { onMounted } from 'vue';
onMounted(() => {
fetchData();
});
样式管理
推荐方案:
- Scoped CSS(组件隔离)
- CSS Modules(通过
<style module>) - Tailwind CSS(实用类优先)
部署构建
生成生产环境代码:
npm run build
输出目录为 dist/,可部署到静态服务器或 CDN。
通过以上步骤,可以快速构建一个功能完整的 Vue.js 页面。根据项目需求,可进一步集成 UI 库(如 Element Plus)、API 请求库(如 Axios)或测试工具(如 Vitest)。






