Skip to content

vue路由原理

vue路由在前端的使用中基本上分为hash模式和history模式,还有一种abstract模式用于SSR

hash模式

hash模式通过改变地址栏中的hash值(也就是#后面的内容)来将hash匹配路由表中的组件

通过window.location.hash属性可以获取和修改地址栏的hash

js
window.location.hash='/home'

console.log(window.location.hash);  // '/home'
js
class Router {
    constructor(config) {
        this.mode = config.mode;
        this.base = config.base || "/";
        this.currentUrl = "";
        this.routes = config.routes || [];
        this.component = null;
        window.addEventListener("load", (e) => this.refresh(e));
        window.addEventListener("hashchange", (e) => this.refresh(e));
    }
    // 匹配路径切换组件
    refresh(e) {
        if (e.type === "load") {
            this.routes.forEach((item) => {
                if (item.path === this.base) {
                    this.component = item.component;
                }
            });
        } else if (e.type === "hashchange") {
            this.routes.forEach((item) => {
                const path = window.location.hash.replace("#", "");
                if (path === item.path) {
                    this.component = item.component;
                }
            });
        }
    }
    push(path) {
        this.currentUrl = path;
        window.location.hash = path;
    }
    go(num) {
        window.history.go(num);
    }
    back() {
        window.history.go(-1);
    }
    forward() {
        window.history.go(1);
    }
}

history模式

MIT Licensed