https://router.vuejs.org/zh/
一 、基础理解
路由:最先从后端中引入,就是根据不同的 url 请求服务器端的资源,由服务器 web server 返回对应页面的详细 html 数据到浏览器中渲染。
前端路由:在不全页面刷新的情况下,实现页面切换效果,主要就是利用到 JS 中的功能,前端路由实现模式通常有:hash 或 history API
URL格式: 协议://主机名:端口/资源路径?查询字符串#hash
hash:hash值的修改不会发送新请求到服务器端。 切换前:#/home 切换后:#/detail
history API:在操作 访问历史时不会发起新的请求到服务器端
VueRouter 是 Vue 的核心插件,主要实现前端路由功能。
二 、安装及引用
$ npm install vue-router --save
创建 VueRouter 对象,并注入 Vue 实例使用
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter) // 使用 VueRouter
const router = new VueRouter({
mode: 'hash', // 路由模式: 'hash' / 'history'
routes: [ // 路由表配置
{
path: '/home', // 路由路径
component: Home // 路由组件
},
{
path: '/mine',
component: Mine
}
]
})
new Vue({
router // 注入 VueRouter
})
三 、$route 与 $router
在使用了 vue-router 的应用中,路由对象会被注入每个组件中,赋值为 this.$route ,并且当路由切换时,路由对象会被更新。
- $route - 代表的是当前正在访问的路由
- $router - 代表的是整个 VueRouter 对象实例(就是注入到 Vue 实例中的 VueRouter 对象)
watch: {
$route (newRoute) {
// console.log('路由变化 ')
this.title = newRoute.meta.title
}
}