Vue Router
Vue Router 是Vue.js的官方插件,用来快速实现单页应用
单页应用
优点:前后端分离开发,提高开发效率、业务场景切换时,局部更新结构、用户体验好,接近本地应用
缺点:不利用SEO、初次首屏加载速度慢、页面复杂度高
前端路由
URL与内容间的映射关系
实现方式
Hash方式
URL中#后面的内容为路由地址,通过location.url切换浏览器中的地址,只改变#之后内容,浏览器不会请求服务器,将地址记录到访问历史中。hash改变后触发hashchange事件进行网页内容更新。
routes保存url和内容处理函数的对应关系;route定义路由规则方法
var router = {
// 保存url和回调函数之间的对应规则
routes : {
},
// 定义路由规则方法
route : function(path,callback){
this.routes[path] = callback;
},
//初始化路由
init:function(){
that = this;
//通过监听hash值变化修改执行函数
window.onhashchange = function(){
var hash = location.hash.replace('#','');
that.routes[hash] && that.routes[hash]()
}
}
}
var content = document.getElementById('content');
//调用函数
router.route('', function () {
content.innerHTML = '这是首页功能';
});
router.route('/category',function(){
content.innerHTML='这是分类功能';
});
router.route('/user',function(){
content.innerHTML='这是用户功能';
});
//调用初始化方法
router.init();
History方式
history方式是H5提供的新方式实现前端路由。由于单页应用中不存在/login这样的页面,所以需要服务端配合除静态资源外都返回单页应用的index.html。通过history.pushState()改变浏览器的地址栏并记录到历史中。不发送请求。监听popstate事件可以监听到浏览器地址变化,根据路由地址找到对应组件进行渲染。
- history.pushState(参数1,参数2,参数3)方法可以更改url内容但不发生跳转,参数1传递数据,参数2传递标题,参数3是跳转到的地址。
- popstate事件监听前进后退的操作,并检测state。需要添加到init方法中。
<script>
go(path){
history.pushState({
path:path},null,path);
this.routes[path] && this.routes[path]();
},
init: function (){
var that = this
window.addEventListener('popstate',function(e){
var path = e.state ? e.state.path : '/'
that.routes[path] && that.routes[path]();
})
}
</script>
由于Hash兼容性更好,VueRouter默认执行Hash模式,利用mode选项设置history模式
var router = new VueRouter({
mode:'history',
router:[
...
]
})
区别总结
原理:Hash是基于锚点以及onhashchange事件,地址发生变化触发onhashchange事件。
History模式基于H5中的HistoryAPI中的history.pushState()(支持IE10以后)和history.replaceState()。history.pushState()方法地址变化时向服务器发送请求。
Vue Router
Vue.js的官方路由管理器,路径切换时加载路径对应组件
基本操作
Vue Router 提供了用于进行路由设置的组件默认为a标签,设置路由连接。用于内容展示。routes 中存储路由中需要的组件,路径为设置的路径时,显示组件中设置的内容。<