vue页面实现
Vue 页面实现基础步骤
创建 Vue 页面需要安装 Vue 环境、编写组件模板、定义逻辑与样式。以下是具体实现方式:
环境准备 确保已安装 Node.js 和 npm/yarn,通过 Vue CLI 或 Vite 初始化项目:
npm init vue@latest # Vue CLI
npm create vite@latest # Vite
单文件组件结构
Vue 页面通常以 .vue 文件组织,包含 <template>, <script>, <style> 三个部分:
<template>
<div class="page-container">
<h1>{{ title }}</h1>
<button @click="handleClick">点击</button>
</div>
</template>
<script>
export default {
data() {
return {
title: 'Vue 页面示例'
}
},
methods: {
handleClick() {
console.log('按钮被点击');
}
}
}
</script>
<style scoped>
.page-container {
padding: 20px;
}
</style>
路由配置实现多页面
安装 Vue Router
npm install vue-router
路由定义示例
在 src/router/index.js 中配置路径与组件映射:
import { createRouter, createWebHistory } from 'vue-router';
import HomePage from '../views/HomePage.vue';
import AboutPage from '../views/AboutPage.vue';
const routes = [
{ path: '/', component: HomePage },
{ path: '/about', component: AboutPage }
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
路由视图占位
在根组件 App.vue 中添加 <router-view>:
<template>
<router-view />
</template>
状态管理(Vuex/Pinia)
Pinia 基础用法 安装 Pinia 并创建 store:
npm install pinia
定义 Store
// 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>
响应式数据处理
组合式 API 示例
使用 ref 和 reactive 管理状态:
<script setup>
import { ref, reactive } from 'vue';
const count = ref(0);
const user = reactive({
name: 'Alice',
age: 25
});
function increaseAge() {
user.age++;
}
</script>
生命周期钩子使用
常用生命周期
<script setup>
import { onMounted, onUnmounted } from 'vue';
onMounted(() => {
console.log('组件挂载完成');
});
onUnmounted(() => {
console.log('组件卸载');
});
</script>
组件间通信
Props 传递数据 父组件传递:
<ChildComponent :message="parentMessage" />
子组件接收:
<script setup>
defineProps({
message: String
});
</script>
事件发射 子组件触发:
<button @click="$emit('notify')">通知</button>
父组件监听:
<ChildComponent @notify="handleNotify" />
样式与作用域
Scoped CSS 限定样式作用域:
<style scoped>
.button {
/* 仅影响当前组件 */
}
</style>
CSS 模块化 通过模块名引用:

<template>
<div :class="$style.redText">文本</div>
</template>
<style module>
.redText {
color: red;
}
</style>






