网站首页 > 教程文章 正文
说到vue-router就表明他只适合于vue和vue是强绑定的关系;不适合其他框架;
现在我们模仿实现一个VueRouter;
1.要使页面刷新;借助vue本身的响应式原理;
import Home from "./views/Home";
import About from "./views/About";
import Vue from "vue";
class VueRouter{
constructor(options){
this.$options = options;
this.routeMap = {}
// 路由响应式 其实很重要的一部分是借助了 vue 的响应式原理 ; 强绑定 ; 必须用在vue上
this.app = new Vue({
data:{
current:"/"
}
})
}
}
VueRouter.install=function(Vue){
//mixin 混入
Vue.mixin({
beforeCreate() {
// this 是vue 实咧
if(this.$options.router){ // 只在跟组件执行一次
Vue.prototype.$router = this.$options.router;
this.$options.router.init()
}
},
})
}
Vue.use(VueRouter)
export default new VueRouter({
routes: [{ path: "/", component: Home }, { path: "/about", component: About }]
})
2.执行上面的init函数;初始化
//这里主要三件事;监听url变化;解析路由配置;实现两个组件
init(){
this.bindEvents() ; //监听url变化
this.createRouteMap(this.$options) ; //解析路由配置
this.initComponent() ; //实现两个组件 router-view router-link
}
3.监听url变化;更新数据
bindEvents(){
window.addEventListener('load',this.onHashChange.bind(this))
window.addEventListener('hashchange',this.onHashChange.bind(this))
}
onHashChange(){
this.app.current = window.location.hash.slice(1) || '/'; // #/about ==> /about
}
4.解析路由配置;
//这个好理解;就是把传进来的路由配置;解析成path-->component的key:value形式
createRouteMap(options){
options.routes.forEach(item=>{
this.routeMap[item.path] = item.component
})
}
5.实现router-link 和 router-view两个组件
initComponent(){
// router-view router-link
Vue.component('router-link',{
props:{to:String},
render(h) {
// h => createElement h(tag,data,children)
return h('a',{attrs:{href:'#'+this.to}},[
this.$slots.default
])
},
});
Vue.component('router-view',{ //这里没有解决路由嵌套的问题 // 全局的组件 任意data 的都会出发全局组件的跟新
render:h=>{
console.log(this.routeMap[this.app.current])
const comp = this.routeMap[this.app.current]
return h(comp)
},
})
}
vue-router的hash模式主要就是监听了hashchange方法;改变当前的路径,再利用vue自身的响应式原理;来刷新视图;
vue-history模式;要服务器配合;访问进来是指向同一个html;代码上处理原理我想和hash应该类似;大家可以自己研究一下;
人到了一定的年龄,一定要懂得,把心情和脾气调成静音模式,然后不动声色的打理自己,过好余生每一天。一路风雨兼程,只为遇见更好的自己,真正能够带你走出黑暗,能够给你带来改变的,就是你自己的内心自信,光明,有拯救自己的责任感动力
- 上一篇: 20道Vue常见面试题,你会几道?
- 下一篇: 机器人是如何通过视觉实现目标跟踪的?
猜你喜欢
- 2024-12-02 20道Vue常见面试题,你会几道?
- 2024-12-02 前端接口防止重复请求实现方案
- 2024-12-02 这些iframe跨域解决方案你需要了解一下,以后不应该再是你的盲区
- 2024-12-02 XSS讲解下(web安全入门11)
- 2024-12-02 2023近期前端面试遇到的题(前端初级)
- 2024-12-02 js基础面试题131-160道题目
- 2024-12-02 js中hash、hashchange事件
- 2024-12-02 IFRAME的各种经验总结
- 2024-12-02 通过 React Router V6 源码,掌握前端路由
- 2024-12-02 layui中的onevent 和event使用方法
- 最近发表
- 标签列表
-
- location.href (44)
- document.ready (36)
- git checkout -b (34)
- 跃点数 (35)
- 阿里云镜像地址 (33)
- qt qmessagebox (36)
- md5 sha1 (32)
- mybatis plus page (35)
- semaphore 使用详解 (32)
- update from 语句 (32)
- vue @scroll (38)
- 堆栈区别 (33)
- 在线子域名爆破 (32)
- 什么是容器 (33)
- sha1 md5 (33)
- navicat导出数据 (34)
- 阿里云acp考试 (33)
- 阿里云 nacos (34)
- redhat官网下载镜像 (36)
- srs服务器 (33)
- pico开发者 (33)
- https的端口号 (34)
- vscode更改主题 (35)
- 阿里云资源池 (34)
- os.path.join (33)