vue-router的使用
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from './views/Home.vue';
Vue.use(VueRouter);
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('./views/About.vue'),
childrend:[
]
}
]
const router = new VueRouter({
routes,
});
const app = new Vue({
el: '#app',
router,
})
vue-router的实现
let Vue;
class VueRouter {
constructor(options){
this.$options = options;
const initial = window.location.hash.slice(1) || '/';
this.routeMap = {};
this.$options.routes.forEach(route => {
this.routeMap[route.path] = route;
})
window.addEventListener('hashchange',()=>{
this.current = window.location.hash.slice(1) || '/'
})
}
}
VueRouter.install = function(_Vue){
Vue = _Vue;
Vue.mixin({
beforeCreate(){
if(this.$options.router){
Vue.prototype.$router = this.$options.router;
}
}
})
Vue.component('router-link',{
props:{
to:{
type: String,
required: true
},
},
render(h){
return <a href={`#${this.to}`}>{this.$slots.default}</a>
return h('a',
{
attrs:{
href: `#${this.to}`
}
},
this.$slots.default
)
}
})
Vue.component('router-view',{
render(h){
const {routeMap, current} = this.$router;
const component = routeMap[current] || null;
return h(component);
}
})
};
export default VueRouter;