获取url参数

    /**
     * 获取url参数
     * name: 可选项,获取某参数,如果不传参将返回参数对象
     */
    getUrlParams(name?) {
        const url = window.location.href;
        const paramList = url.split('?')[1]?.split('&');
        const params = {};
        paramList.forEach(ite => {
            const arr = ite.split('=');
            Object.assign(params, {
                [arr[0]]: arr[1]
            })
        });
        if (name) {
            return params[name];
        } else {
            return params;
        }
    }

// demo
// url: https://i.cnblogs.com/posts/add?id=1234
getUrlParams();
// 返回 {id: 1234}

getUrlParams(‘id’);
// 返回 1234
 
 
原文地址:https://www.cnblogs.com/jing5990/p/15723418.html