vue单页面简单实现
Vue 单页面应用基础实现
创建 Vue 单页面应用(SPA)需要以下核心步骤:
安装 Vue CLI 使用 Vue CLI 快速搭建项目结构:
npm install -g @vue/cli
vue create my-project
项目结构说明 关键文件及目录:
src/main.js:应用入口文件src/App.vue:根组件src/router/index.js:路由配置(需安装 vue-router)src/views/:页面级组件目录src/components/:可复用组件目录
路由配置示例 安装路由并配置基础路径:
npm install vue-router
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
基础组件示例 创建页面组件:
<!-- src/views/Home.vue -->
<template>
<div class="home">
<h1>首页内容</h1>
<router-link to="/about">跳转到关于页</router-link>
</div>
</template>
<script>
export default {
name: 'HomeView'
}
</script>
挂载路由到应用 修改主入口文件:
// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')
根组件模板
<!-- src/App.vue -->
<template>
<div id="app">
<nav>
<router-link to="/">首页</router-link> |
<router-link to="/about">关于</router-link>
</nav>
<router-view/>
</div>
</template>
关键注意事项
开发环境运行 启动开发服务器:
npm run serve
生产环境构建 生成优化后的静态文件:
npm run build
组件通信方式
- Props 向下传递数据
- 自定义事件向上传递消息
- Vuex/Pinia 状态管理(复杂场景)
动态路由实现
// 路由配置中添加
{
path: '/user/:id',
component: User
}
获取路由参数 在组件中使用:
this.$route.params.id // Vue 2.x
import { useRoute } from 'vue-router'
const route = useRoute() // Vue 3.x
进阶功能扩展
添加状态管理 安装 Pinia(推荐):
npm install pinia
配置全局样式
在 main.js 中导入:
import './assets/css/global.css'
处理异步加载 使用路由懒加载提升性能:
component: () => import('./views/About.vue')
添加页面过渡效果 在 App.vue 中使用:
<router-view v-slot="{ Component }">
<transition name="fade">
<component :is="Component" />
</transition>
</router-view>
以上实现涵盖了 Vue SPA 的基础架构,可根据实际需求扩展更多功能模块。







