vue项目实现页面
Vue 项目实现页面的基本方法
创建 Vue 组件
在 Vue 项目中,页面通常由组件构成。创建一个 .vue 文件,包含模板、脚本和样式三部分。
<template>
<div class="page">
<h1>{{ title }}</h1>
</div>
</template>
<script>
export default {
data() {
return {
title: '页面标题'
}
}
}
</script>
<style scoped>
.page {
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
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
动态路由传参
通过路由参数实现动态页面内容。
// 路由配置
{
path: '/detail/:id',
name: 'Detail',
component: DetailPage
}
<!-- 页面组件中获取参数 -->
<script>
export default {
computed: {
id() {
return this.$route.params.id
}
}
}
</script>
页面布局管理
使用嵌套路由实现公共布局。
{
path: '/',
component: Layout,
children: [
{
path: '',
component: HomePage
},
{
path: 'about',
component: AboutPage
}
]
}
页面过渡效果
通过 Vue 的过渡组件实现页面切换动画。
<template>
<router-view v-slot="{ Component }">
<transition name="fade">
<component :is="Component" />
</transition>
</router-view>
</template>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
页面状态管理
对于跨组件状态共享,可以使用 Pinia 或 Vuex。
// store/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
}
}
})
<!-- 页面中使用 -->
<script>
import { useCounterStore } from '../store/counter'
export default {
setup() {
const counter = useCounterStore()
return { counter }
}
}
</script>
页面生命周期
利用 Vue 生命周期钩子处理页面特定逻辑。
<script>
export default {
mounted() {
console.log('页面加载完成')
},
unmounted() {
console.log('页面卸载')
}
}
</script>
响应式设计
通过 CSS 媒体查询实现页面响应式布局。
@media (max-width: 768px) {
.page {
padding: 10px;
}
}
页面性能优化
使用懒加载提升页面加载速度。
{
path: '/about',
component: () => import('../views/AboutPage.vue')
}






