vue-router 原理解析
使用
安装:
vue add router
配置路由:
{ path: '/', name: 'home', component: Home }
添加导航链接:
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
挂载:
new Vue({
render: h => h(App),
router,
}).$mount('#app')
动态路由:
把某种模式匹配到的所有路由,全都映射到同一个组件。
<template>
<div>
<h2>商品详情</h2>
<p>{{$route.params.id}}</p>
</div>
</template>
{
path: '/detail/:id',
name: 'detail',
component: Detail
}
<div v-for="item in items" :key="item.id">
<router-link :to="`/detail/${item.id}`">
{{ item.name }}
</router-link>
</div>
{
path: '/',
name: 'home',
component: Home,
children: [{
path: '/detail/:id',
name: 'detail',
component: Detail
}]
}
<template>
<div class="home">
<h1>首页</h1>
<router-view></router-view>
</div>
</template>
要理解vue-router 原理,可以先从一下几方面入手:
- 路由解析配置
- url响应
- 事件监听(
hashchange ) - 组件如何切换
原理简单实现
let Vue;
class LeoRouter {
constructor(options) {
this.$options = options;
this.routeMap = {};
this.app = new Vue({
data: {
current: "/"
}
})
}
init() {
this.bindEvents();
this.createRouteMap();
this.initComponent();
}
bindEvents() {
window.addEventListener("load", this.onHashChange.bind(this), false);
window.addEventListener("hashchange", this.onHashChange.bind(this), false);
}
onHashChange() {
this.app.current = window.location.hash.slice(1) || '/';
}
createRouteMap() {
this.$options.routes.forEach(item => {
this.routeMap[item.path] = item;
})
}
initComponent() {
Vue.component("leo-link", {
props: {
to: String,
},
render(h) {
return h('a', {attrs: {href: '#'+this.to}}, [this.$slots.default])
}
});
Vue.component("leo-view", {
render: h => {
const component = this.routeMap[this.app.current].component;
return h(component);
}
})
}
}
LeoRouter.install = function(_Vue) {
Vue = _Vue;
Vue.mixin({
beforeCreate() {
if(this.$options.router) {
Vue.prototype.$router = this.$options.router;
this.$options.router.init();
}
}
})
}
export default LeoRouter;
|