VueRouter是什么?
路由
广义解释:
route:从起点到终点所采取的方式或路线。
router:将数据包转发到计算机网络的适当部分的设备。
通常认为:
路由器,网络包的二传手,进出的包采用同一种协议。
本文含义:
不刷新页面的情况下,根据URL跳转到指定的“界面”。
传统界面的跳转和路由跳转的区别
- 路由用于设定访问路径,并将路径和组件映射起来,没有刷新界面。
- 传统的页面应用,是用一些超链接来实现页面切换和跳转的,需要刷新界面。
浏览器无刷新改变路由的方法
通过hash改变路由
window.location.hash='edit'
怎样监听hash变化?
通过hash改变了url,会触发hashchange事件,只要监听hashchange事件,就能捕获到通过hash改变url的行为。
window.onhashchange=function(event){
console.log(event);
}
//或者
window.addEventListener('hashchange',function(event){
console.log(event);
})
通过history改变路由
会刷新界面
- history.back() : 返回浏览器会话历史中的上一页,跟浏览器的回退按钮功能相同
- history.forward() :指向浏览器会话历史中的下一页,跟浏览器的前进按钮相同
- history.go() : 可以跳转到浏览器会话历史中的指定的某一个记录页
不会刷新界面
- history.pushState() 可以将给定的数据压入到浏览器会话历史栈中,该方法接收3个参数,对象,title和一串url。pushState后会改变当前页面url。在浏览器当前页面之上压入一个界面信息。可以返回当前页信息。
- history.replaceState() 将当前的会话页面的url替换成指定的数据,replaceState后也会改变当前页面的url。使用这种方法,浏览器当前页的信息被替换以后是无法被复原的。
怎样监听history改变路由的变化?
- 监听back/forward/go
// 如果是history.back(),history.forward()、history.go()那么会触发popstate事件
window.addEventListener('popstate', function(event) {
console.log(event);
})
- 监听pushState/replaceState
history.pushState()和history.replaceState()不会触发popstate事件,所以需要自己手动增加事件。怎样做呢?可以通过在方法里面主动的去触发popstate事件。另一种就是在方法中创建一个新的全局事件。
const _historyWrap = function(type) {
const orig = history[type];
const e = new Event(type);
return function() {
const rv = orig.apply(this, arguments);
e.arguments = arguments;
window.dispatchEvent(e);
return rv;
};
};
history.pushState = _historyWrap('pushState');
history.replaceState = _historyWrap('replaceState');
监听:
window.addEventListener('pushState', function(e) {
console.log('change pushState');
});
window.addEventListener('replaceState', function(e) {
console.log('change replaceState');
});
单页面应用怎样刷新界面?
在点击不同的link的时候,我们的Vue应用也是会跳转"界面"的,当然这期间肯定是有刷新的过程。Vue应用怎样实现的"界面"刷新呢?
Vue应用并没有刷新界面,我们所见到的刷新的是组件,在Vue中一个组件可以单独被渲染成一个界面。
routerView也是一个组件
我们将项目搭建起来之后,会通过这种方式使用路由。
<div id="app">
<router-link to="/bar">Bar</router-link>
<router-view></router-view>
</div>
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const Bar = { template: '<div>bar</div>' }
const routes = [
{ path: '/bar', component: Bar }
]
const router = new VueRouter({
routes
})
const app = new Vue({
el: '#app',
router
})
使用路由的时候,我们通过标签来渲染匹配的。