vue实现页面
Vue 实现页面的基本方法
创建 Vue 项目
使用 Vue CLI 快速初始化项目,运行以下命令安装并创建项目:
npm install -g @vue/cli
vue create my-project
编写单文件组件
Vue 页面通常由单文件组件(.vue文件)构成,包含模板、脚本和样式:
<template>
<div class="page-container">
<h1>{{ title }}</h1>
<button @click="handleClick">点击事件</button>
</div>
</template>
<script>
export default {
data() {
return {
title: 'Vue页面示例'
}
},
methods: {
handleClick() {
alert('事件触发');
}
}
}
</script>
<style scoped>
.page-container {
padding: 20px;
}
</style>
路由配置
通过 Vue Router 实现页面导航,在 router/index.js 中定义路由:
import { createRouter, createWebHistory } from 'vue-router';
import HomePage from '../views/HomePage.vue';
const routes = [
{ path: '/', component: HomePage }
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
状态管理(可选)
复杂页面可使用 Pinia 或 Vuex 管理全局状态:
// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++;
}
}
});
页面生命周期
利用生命周期钩子处理异步数据:
export default {
async created() {
const res = await fetch('api/data');
this.data = await res.json();
}
}
响应式样式
结合 CSS 预处理器(如 SCSS)编写样式:
<style lang="scss">
$primary-color: #42b983;
.page-container {
h1 {
color: $primary-color;
}
}
</style>
组件通信
父子组件通过 props 和 emits 交互:
<!-- 父组件 -->
<ChildComponent :msg="parentMsg" @update="handleUpdate"/>
<!-- 子组件 -->
<script>
export default {
props: ['msg'],
emits: ['update'],
methods: {
sendUpdate() {
this.$emit('update', newValue);
}
}
}
</script>






