什么是 Vue-Router
Vue-Router 是 Vue 的一个插件库,专门用来实现 SPA 应用。
什么是 SPA
- 单页面 Web 应用(single page web application)
- 整个应用只有一个完整的页面
- 点击页面中的导航链接不会刷新页面,只会做页面的局部更新。
- 数据需要通过 Ajax 请求获取。
路由分类
- 后端路由:value 是 function,服务器收到一个请求,根据路径找到匹配的函数来处理请求,返回响应数据。
- 前端路由:value 是 component,当浏览器路径改变时,对应的组件就会显示。
使用
router/index.js
import Vue-Router from 'vue-router'
import About from '../component/about'
import Home from '../component/home'
export default new Router({
router:[
{
path:'/about',
component:'About'
}
{
path:'/home',
component:'Home'
}
]
})
<router-link to='/about' active-class='active'></router-link>
实现路由的切换
<router-view></router-view>
实现内容的显示
多级路由
export default new Router({
router:[
{
path:'/about',
component:'About'
}
{
path:'/home',
component:'Home',
children:[
{
path:'news'
component:'News'
},
{
path:'message'
component:'Message'
}
]
}
]
})
<router-link to='/home/news' active-class='active'></router-link>
以上注意 path 中不要写 '/news',因为 Vue-Router 中已经会解析出
/home/news
,不需要多加“/”,在router-link 中要写全路径/home/news
,不能只写/news
。
注意
- 路由组件通常存放在
pages
文件夹,一般组件通常存放在components
文件夹。 - 通过切换,不需要被显示的路由组件是默认被销毁的,需要时再去挂载。
- 每个组件都有自己的 $route 属性,内容是自己的路由信息。
- 整个应用只有一个 router,可以通过组件的 $router 属性获取到。
更多精彩内容:各种AI课程、技能课程、黑科技软件、网站小程序源码、副业小项目、PPT模板等精品素材、电商课程、推广引流课程等,尽在 天边资源网 。