Vue全家桶之Vue-Router
一.使用
1.引入
import VueRouter from "vue-router";
Vue.use(VueRouter);
2.创建router实例
import Home from "./components/Home.vue";
import About from "./components/About.vue";
const routes = [
{ path: "/", component: Home },
{ path: "/about", component: About },
];
const router = new VueRouter({
routes,
});
3.在根组件上添加该实例
new Vue({
render: (h) => h(App),
router,
}).$mount("#app");
Vue-Router简单实现
let Vue;
class MyRouter {
// {routes}
constructor(options) {
this.$options = options;
const initial = "/" + window.location.hash.slice(1);
Vue.util.defineReactive(this, "current", initial);
window.addEventListener("hashchange", () => {
this.current = "/" + window.location.hash.slice(1);
});
}
}
MyRouter.install = function (_Vue) {
Vue = _Vue;
Vue.mixin({
beforeCreate() {
if (this.$options.router) {
Vue.prototype.$router = this.$options.router;
}
},
});
Vue.component("router-link", {
mounted() {},
props: ["to"],
render(h) {
return (
<a style="margin:10px" href={this.to}>
{this.$slots.default}
</a>
);
},
});
Vue.component("router-view", {
render(h) {
const current = this.$router.$options.routes.find(
(item) => item.path == this.$router.current
);
return h(current.component);
},
});
};
export default MyRouter;