此文件用于操作 ajax中url链接使用,不作为vue路由操作方法
/**
* 此文件用于操作 ajax中url链接使用,不作为vue路由操作方法
* 调用方法:
* import {usitripUrl} from url.js
* var url = new objURL( "xxx.url" );
* url.get("a")
*/
export const usitripUrl = function(url) {
this.ourl = url || window.location.href;
this.href = ""; //?前面部分
this.params = {}; //url参数对象
this.jing = ""; //#及后面部分
this.init();
};
//分析url,得到?前面存入this.href,参数解析为this.params对象,#号及后面存入this.jing
usitripUrl.prototype.init = function() {
var str = this.ourl;
var index = str.indexOf("#");
if (index > 0) {
this.jing = str.substr(index);
str = str.substring(0, index);
}
index = str.indexOf("?");
if (index > 0) {
this.href = str.substring(0, index);
str = str.substr(index + 1);
var parts = str.split("&");
for (var i = 0; i < parts.length; i++) {
var kv = parts[i].split("=");
this.params[kv[0]] = kv[1];
}
} else {
this.href = this.ourl;
this.params = {};
}
};
//得到参数值
usitripUrl.prototype.get = function(key) {
return this.params[key];
};
//只是修改this.params
usitripUrl.prototype.set = function(key, val) {
this.params[key] = val;
return this.url();
};
//只是设置this.params
usitripUrl.prototype.remove = function(key) {
this.params[key] = undefined;
return this.url();
};
//根据三部分组成操作后的url
usitripUrl.prototype.url = function() {
var strurl = this.href;
var objps = []; //这里用数组组织,再做join操作
var tmp = [];
for (var k in this.params) {
if (this.params[k]) {
if(k == 'language_code'){
tmp.push(this.params[k]);
}else{
objps.push(k + "=" + this.params[k]);
}
}
}
if(tmp.length){
objps.push('language_code' + "=" + tmp[0]);
}
if (objps.length > 0) {
strurl += "?" + objps.join("&");
}
if (this.jing.length > 0) {
strurl += this.jing;
}
return strurl;
};