vue项目实现页面
Vue项目实现页面的基本方法
创建Vue组件
使用Vue单文件组件(SFC)方式组织页面结构,每个.vue文件包含<template>、<script>和<style>三个部分。例如创建HomePage.vue:
<template>
<div class="page-container">
<h1>{{ title }}</h1>
<button @click="handleClick">点击按钮</button>
</div>
</template>
<script>
export default {
data() {
return {
title: '首页'
}
},
methods: {
handleClick() {
console.log('按钮被点击')
}
}
}
</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: '/',
name: 'Home',
component: HomePage
},
{
path: '/about',
name: 'About',
component: () => import('../views/AboutPage.vue')
}
]
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++
}
}
})
页面布局
通过组合式API实现可复用的页面布局逻辑:

<script setup>
import { ref } from 'vue'
const loading = ref(false)
const fetchData = async () => {
loading.value = true
// API调用...
loading.value = false
}
</script>
<template>
<div v-if="loading">加载中...</div>
<div v-else>
<!-- 页面内容 -->
</div>
</template>
动态组件
根据条件渲染不同页面组件:
<template>
<component :is="currentComponent" />
</template>
<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
export default {
data() {
return {
currentComponent: 'ComponentA'
}
},
components: {
ComponentA,
ComponentB
}
}
</script>
页面过渡效果
为页面切换添加过渡动画:
<template>
<router-view v-slot="{ Component }">
<transition name="fade" mode="out-in">
<component :is="Component" />
</transition>
</router-view>
</template>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
页面优化技巧
懒加载组件
使用异步组件减少初始加载时间:

const AboutPage = () => import('./AboutPage.vue')
路由守卫
通过路由守卫控制页面访问权限:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated()) {
next('/login')
} else {
next()
}
})
页面元信息
动态设置页面标题等元信息:
router.afterEach((to) => {
document.title = to.meta.title || '默认标题'
})
错误处理
全局错误处理页面:
<template>
<div v-if="error">
{{ error.message }}
<button @click="retry">重试</button>
</div>
</template>
<script>
export default {
data() {
return {
error: null
}
},
errorCaptured(err) {
this.error = err
return false
},
methods: {
retry() {
this.error = null
// 重试逻辑
}
}
}
</script>






