前端路由和后端路由的区别
后端路由:
输入url>>请求发送到服务器>>服务器解析请求的路径>>拿到对应的页面>>返回回去
前端路由:
输入url>>js解析地址>>找到对应地址的页面>>执行页面生成的js>>看到页面
vue-router工作流程
Hash与History
Hash
1、链接中带有#,#后的就是hash的内容,改变hash不会去向后端发起请求
2、可以通过location.hash拿到hash内容
3、可以通过onhashchange监听hash的改变
history
1、正常的路径,修改会发起请求
2、可以通过location.pathname拿到history内容
3、可以通过onpopstate监听history变化
vue-router
vue-router为一个外部插件,并不是vue本身的东西
src下创建myrouter文件夹,index.js
class HistoryRoute{
constructor(){
//当前路径
this.current = null;
}
}
class vueRouter{
constructor(options){
//模式,默认hash
this.mode = options.mode || 'hash';
this.routes = options.routes || [];
this.history = new HistoryRoute;
this.routesMap = this.createMap(this.routes);
this.init();
}
init(){
if(this.mode=="hash"){
//自动加上#
location.hash?"":location.hash="/";
window.addEventListener("load",()=>{
//第一次加载,监听hash
this.history.current = location.hash.slice(1);
})
window.addEventListener("hashchange",()=>{
this.history.current = location.hash.slice(1);
})
}
if(this.mode=="history"){
window.addEventListener("load",()=>{
//第一次加载,监听history
this.history.current = location.pathname;
})
window.addEventListener("popstate",()=>{
this.history.current = location.pathname;
})
}
}
//routes数据格式转换,{path:组件名}的形式
createMap(routes){
return routes.reduce((memo,current)=>{
memo[current.path] = current.component;
return memo;
},{})
}
}
vueRouter.install = function(vue){
vue.mixin({//从父组件到子组件依次混入
//在组件还没有生成,数据没有渲染之前混入
beforeCreate(){
if(this.$options&&this.$options.router){//this指向当前组件
//第一次进来是main.js中的new Vue部分
this._root = this;
this._router = this.$options.router;
//监听current
vue.util.defineReactive(this,'current',this._router.history);
}else{
//后面进来的组件,指向根实例
this._root = this.$parent._root;
}
//将_root的内容绑定到$router和$route上
//多人合作,防止数据篡改,所以只设置读取,不许修改
Object.defineProperty(this, '$router', {
get() {
return this._root._router;
}
})
Object.defineProperty(this, '$route', {
get() {
return this._root._router.history.current;
}
})
}
})
//注册router-view全局组件
vue.component('router-view',{
render(h){
let current = this._self._root._router.history.current;
let routeMap = this._self._root._router.routesMap;
return h(routeMap[current]);
}
})
}
export default vueRouter;
router文件夹中修改index.js
import Vue from 'vue'
import Router from '../myrouter'
import HelloWorld from '@/components/HelloWorld'
import Test from '@/components/Test'
Vue.use(Router)
export default new Router({
mode: "hash",//模式
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/test',
name: 'Test',
component: Test
}
]
})
页面效果