基本用法
引入vue-router
import Router from "vue-router";
Vue.use(Router);
创建路由实例
const router = new Router({
mode: "history",
routes: [{
path: '/', component: Home
}, {
path: '/about', component: About
}]
});
配置到Vue的根组件
new Vue({
router,
render: h => h(App),
}).$mount('#app')
界面上使用
<div id="app">
<div>
<router-link to="/">home</router-link>
<router-link to="/about">about</router-link>
</div>
<router-view></router-view>
</div>
根据用法反推实现原理
- 通过第一步
import
可以猜测,vue-router
应该是会export出一个class类
- 根据
Vue.use
可以猜测,vue-router
里面会包含一个install
方法 - 需要监听url的变化渲染不同的组件
- 在界面上使用到
<router-view></router-view>
和<router-link></route-link>
两个组件,所以vue-router
应该会实现这两个组件
实现vue-router
实现VueRouter类
class VueRouter {
constructor(options) {
this.$options = options
this.routeMap = {}
this.app = new Vue({
data: {
current: '/'
}
});
}
init(){
this.bindEvents()
this.createRouteMap(this.$options)
this.initComponent()
}
bindEvents(){
window.addEventListener('load', this.onHashChange.bind(this))
window.addEventListener('hashchange', this.onHashChange.bind(this))
}
onHashChange() {
this.app.current = window.location.hash.slice(1) || '/'
}
createRouteMap(options){
options.routes.forEach(item => {
this.routeMap[item.path] = item.component
});
}
initComponent(){
Vue.component('router-link', {
props: {
to: String
},
render(h) {
return h('a', { attrs: { href: "#" + this.to } }, [
this.$slots.default
])
}
})
Vue.component('router-view', {
render:h => {
const comp = this.routeMap[this.app.current]
return h(comp)
}
})
}
}
实现install方法
VueRouter.install = function (Vue) {
Vue.mixin({
beforeCreate() {
if (this.$options.router) {
Vue.prototype.$router = this.$options.router
this.$options.router.init()
}
}
})
}
验证
import Home from './views/Home'
import About from './views/About'
import VueRouter from './mrouter'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [{ path: "/", component: Home }, { path: "/about", component: About }]
})
new Vue({
router,
render: h => h(App),
}).$mount('#app')
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</div>
<router-view />
</div>
效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200331230251645.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2h5cGluMTIz,size_16,color_FFFFFF,t_70)