美文网首页
js取地址栏参数 (涵盖可能会有中文)

js取地址栏参数 (涵盖可能会有中文)

作者: 小石头糖糖 | 来源:发表于2020-06-16 14:14 被阅读0次

一、传统js方法:

S1: 在工具包中 (如:utils/common中) 封装getQueryString函数:

/*name为要取的参数字段*/
var getQueryString = function (name) {
    var url=window.location.search;
    // 若在react-router中:
    // var url = this.props.location.search;

    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = url.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;
    // 若参数中可能有中文: 
    // return r ? decodeURIComponent(r[2]) : null;
};
export { getQueryString };

S2: 使用方法:

import { getQueryString } from "../utils/common";
/*取 name*/
const name = getQueryString("name");

此方法在vue中hash模式下会取到null,在routes中设为history模式即可:
mode:'history'

二、vue-router中:

const name = this.$route.query.name;

相关文章

网友评论

      本文标题:js取地址栏参数 (涵盖可能会有中文)

      本文链接:https://www.haomeiwen.com/subject/mtzbzhtx.html