单应用程序
SPA - Single Page Application
所有功能在一个html页面上实现
单页面应用 多用于 系统类网站/内部网站/文档类网站/移动端站点
多页面应用 多用于 公司官网/电商类网站
路由
单页面应用按需更新页面,需要明确访问路径和组件的对应关系
Vue中的路由就是路由和组件的映射关系
VueRouter的基本使用
作用:修改地址栏路径时,切换显示匹配的组件
说明:Vue官方的一个路由插件,是一个第三方包
Vue2 对应VueRouter3.x
Vue3 对应 VueRouter4.x
使用步骤
- 下载 yarn add vue-router@3.6.5
- 引入 import VueRouter from 'vue-router'
- 安装注册 Vue.use(VueRouter)
- 创建路由对象 const router=new VueRouter()
- 注入,将路由对象注入到new Vue实例中,建立关联
new Vue({
render: h => h(App),
router
}).$mount('#app')
核心步骤
创建需要的组件(view目录),配置路由规则
配置导航,配置路由出口(路径匹配的组件的显示位置)
效果
代码
Find.vue
<template>
<div>
<p>发现音乐</p>
<p>发现音乐</p>
<p>发现音乐</p>
<p>发现音乐</p>
</div>
</template>
<script>
export default {
name: 'FindMusic'
}
</script>
<style>
</style>
Friend.vue
<template>
<div>
<p>我的朋友</p>
<p>我的朋友</p>
<p>我的朋友</p>
<p>我的朋友</p>
</div>
</template>
<script>
export default {
name: 'MyFriend'
}
</script>
<style>
</style>
My.vue
<template>
<div>
<p>我的音乐</p>
<p>我的音乐</p>
<p>我的音乐</p>
<p>我的音乐</p>
</div>
</template>
<script>
export default {
name: 'MyMusic'
}
</script>
<style>
</style>
App.vue
<template>
<div>
<div class="footer_wrap">
<a href="#/find">发现音乐</a>
<a href="#/my">我的音乐</a>
<a href="#/friend">朋友</a>
</div>
<div class="top">
<!-- 路由出口 → 匹配的组件所展示的位置 -->
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {};
</script>
<style>
body {
margin: 0;
padding: 0;
}
.footer_wrap {
position: relative;
left: 0;
top: 0;
display: flex;
width: 100%;
text-align: center;
background-color: #333;
color: #ccc;
}
.footer_wrap a {
flex: 1;
text-decoration: none;
padding: 20px 0;
line-height: 20px;
background-color: #333;
color: #ccc;
border: 1px solid black;
}
.footer_wrap a:hover {
background-color: #555;
}
</style>
main.js
import Vue from 'vue'
import App from './App.vue'
// 路由的使用步骤 5 + 2
// 5个基础步骤
// 1. 下载 v3.6.5
// 2. 引入
// 3. 安装注册 Vue.use(Vue插件)
// 4. 创建路由对象
// 5. 注入到new Vue中,建立关联
// 2个核心步骤
// 1. 建组件(views目录),配规则
// 2. 准备导航链接,配置路由出口(匹配的组件展示的位置)
import Find from './views/Find'
import My from './views/My'
import Friend from './views/Friend'
import VueRouter from 'vue-router'
Vue.use(VueRouter) // VueRouter插件初始化
const router = new VueRouter({
// routes 路由规则们
// route 一条路由规则 { path: 路径, component: 组件 }
routes: [
{ path: '/find', component: Find },
{ path: '/my', component: My },
{ path: '/friend', component: Friend },
]
})
Vue.config.productionTip = false
new Vue({
render: h => h(App),
router
}).$mount('#app')
组件目录存放问题
组件分类:页面组件、复用组件
分类放更易维护
页面组件
src/views
页面展示,配合路由使用
复用组件
src/components
展示数据,常用于复用