什么是路由
-
对于普通的网站,所有的超链接都是URL地址,所有的URL地址都对应服务器上对应的资源;
-
对于单页面应用程序来说,主要通过URL中的hash(#号)来实现不同页面之间的切换,同时,hash有一个特点:HTTP请求中不会包含hash相关的内容;所以,单页面程序中的页面跳转主要用hash实现.
-
在单页面应用程序中,这种通过hash改变来切换页面的方式,称作前端路由(区别于后端路由);
在 vue 中使用 vue-router
导入 vue-router 组件类库:
先要导入vue ,再导入 vue-router
组件类库
<script src="./lib/vue-router-2.7.0.js"></script>
使用 router-link 组件来导航
<router-link to="/login">登录</router-link>
<router-link to="/register">注册</router-link>
使用 router-view
组件来显示匹配到的组件
<router-view></router-view>
使用 Vue.extend
来创建登录组件
var login = Vue.extend({
template: '<h1>登录组件</h1>'
});
使用 Vue.extend
来创建注册组件
var register = Vue.extend({
template: '<h1>注册组件</h1>'
});
创建一个路由 router
实例,通过 routers
属性来定义路由匹配规则
var router = new VueRouter({
routes: [
{ path: '/login', component: login },
{ path: '/register', component: register }
]
});
创建 Vue 实例,得到 ViewModel
var vm = new Vue({
el: '#app',
router: router // 使用 router 属性来使用路由规则
简写:router
});
Vue 路由中 hash 模式和 history 模式区别
hash模式
hash 出现在 URL 中,但不会被包含在 http 请求中,对后端完全没有影响,因此改变 hash 不会重新加载页面。
特点:hash虽然在URL中,但不被包括在HTTP请求中;用来指导浏览器动作,hash不会重加载页面。
history模式
history
利用了 html5 history interface
中新增的 pushState()
和 replaceState()
方法。这两个方法应用于浏览器记录栈,在当前已有的 back、forward、go
基础之上,它们提供了对历史记录修改的功能。只是当它们执行修改时,虽然改变了当前的 URL
,但浏览器不会立即向后端发送请求。
原理:
hash
模式的原理是 onhashchange
事件,可以在 window
对象上监听这个事件。
history
:hashchange
只能改变 #
后面的代码片段,history
api
(pushState、replaceState、go、back、forward)
则给了前端完全的自由,通过在window
对象上监听popState()
事件。
Vue 路由中 $route
和 $router
的区别
$route是“路由信息对象”,包括path,params,hash,query,fullPath,matched,name等路由信息参数。
$router是“路由实例”对象包括了路由的跳转方法,钩子函数等。