本文主要是介绍Vue 进阶 [五] 手写VueRouter,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
人生当自勉,学习需坚持。
定义
Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:
- 嵌套的路由/视图表
- 模块化的、基于组件的路由配置
- 路由参数、查询、通配符
- 基于 Vue.js 过渡系统的视图过渡效果
- 细粒度的导航控制
- 带有自动激活的 CSS class 的链接
- HTML5 历史模式或 hash 模式,在 IE9 中自动降级
- 自定义的滚动条行为
VueRouter使用的核心步骤
步骤一:使用vue-router 插件,router.js
import Router from 'vue-router'
Vue.use(Router)
步骤二:创建Router 实例,router.js
export default new Router({...})
步骤三:在组件上添加该实例,main.js
import router from './router'
new Vue({
router,
}).$mount("#app");
步骤四:添加路由视图 App.vue
<router-view></router-view>
导航:
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
vue-router 手动实现
需求分析
- 作为一个插件存在:实现VueRouter类和install方法
- 实现两个全局组件:router-view用于显示匹配组件内容,router-link用于跳转
- 监控url变化:监听hashchange或popstate事件
- 响应最新url:创建一个响应式的属性current,当它改变时获取对应组件并显示
实现一个插件:创建VueRouter类和install方法
let Vue; // 引用构造函数,VueRouter中要使用
// 保存选项
class VueRouter {
constructor(options) {
this.$options = options;
}
}
// 插件:实现install方法,注册$router
VueRouter.install = function(_Vue) {
// 引用构造函数,VueRouter中要使用
Vue = _Vue;
Vue.mixin({
beforeCreate() {
// 只有根组件拥有router选项
if (this.$options.router) {
// vm.$router
Vue.prototype.$router = this.$options.router;
}
}
});
};
export default VueRouter;
创建router-view和router-link
zrouter-link.js
export default {props: {to: {type: String,required: true},},render(h) {// <a href="#/about">abc</a>// <router-link to="/about">xxx</router-link>// h(tag, data, children)console.log(this.$slots);return h('a', {attrs: {href: '#' + this.to}}, this.$slots.default)// return <a href={'#' + this.to}>{this.$slots.default}</a>}
}
zrouter-view.js
export default {render(h) {//获取path对应的componentconst {routeMap,current} = this.$router;console.log(routeMap, current);const component = routeMap[current].component || null;return h(component)}
}
监控url变化
定义响应式的current属性,监听hashchange事件
class VueRouter {
constructor(options) {
// current应该是响应式的
Vue.util.defineReactive(this, 'current', '/')
// 定义响应式的属性current
const initial = window.location.hash.slice(1) || '/'
Vue.util.defineReactive(this, 'current', initial)
// 监听hashchange事件
window.addEventListener('hashchange', this.onHashChange.bind(this))
window.addEventListener('load', this.onHashChange.bind(this))
}
onHashChange() {
this.current = window.location.hash.slice(1)
}
}
创建路由映射表
//创建一个路由映射表this.routeMap = {}options.routes.forEach(route => {this.routeMap[route.path] = route})
较完整代码
import Link from './zrouter-link'
import View from './zrouter-view'
//1、实现一个插件:挂载$router ==>实现install 方法
let Vue
class ZVueRouter {constructor(options) {this.$options = options//需要创建响应式的current属性Vue.util.defineReactive(this, 'current', '/')// this.current = '/'// 监听URL的变化window.addEventListener('hashchange', this.onHashChange.bind(this))window.addEventListener('load', this.onHashChange.bind(this))//创建一个路由映射表this.routeMap = {}options.routes.forEach(route => {this.routeMap[route.path] = route})}onHashChange() {console.log(window.location.hash)this.current = window.location.hash.slice(1)}
}
ZVueRouter.install = function (_Vue) {//保存构造函数,在ZVueRouter中使用Vue = _Vue//挂载$router// 怎么获取根实例中的router 选项 使用全局混入//Vue.mixin({//此处写的生命周期的钩子 会在所有组件中都执行一遍beforeCreate() {// console.log(this)// 确保根实例的时候才执行if (this.$options.router) {Vue.prototype.$router = this.$options.router}},})//任务2、实现两个全局组件router-link 和 router-view// Vue.component('router-link', {// props: {// to: {// type: String,// required: true,// },// },// render(h) {// // 希望渲染出一个a 标签// // h(tag,data,children)// //<router-link to='/about'></router-link>// // console.log(this.$slots)// return h('a', {// attrs: {// href: "#" + this.to// }// }, this.$slots.default)// },// })// Vue.component('router-view', {// render(h) {// // 获取path 对应的component// // let component = null// console.log(this)// console.log('router-view this.$router', this.$router)// // this.$router.$options.routes.forEach((route) => {// // if (route.path === this.$router.current) {// // component = route.component// // }// // })// // 以上这样写每次渲染都需要遍历找一遍 优化// const {// routeMap,// current// } = this.$router// const component = routeMap[current].component || null;// return h(component)// },// })// 将router-link router-view 单抽取出来Vue.component('router-link', Link)Vue.component('router-view', View)}
export default ZVueRouter
代码地址
https://gitee.com/xiaozhidayu/vue-study-component
https://gitee.com/xiaozhidayu/vue-study-component.git
人生就是一场马拉松。领先时不必沾沾自喜,落后时也不用慌乱着急,此刻的得失成败,不代表最终的成绩。把鲜花和掌声当作前进的动力,把挫折和失败化为奋进的勇气,只要不放弃,再平凡的人生也能创造奇迹
这篇关于Vue 进阶 [五] 手写VueRouter的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!