【发布时间】:2017-12-12 12:46:14
【问题描述】:
我正在使用 Vue,但 我没有使用 vue-router。
如何获取 URI 参数?
我找到了一种使用 root el 属性获取 URI 的方法。
但是有什么合适的方法来获取我想要发送的参数 后端并从服务器获取响应并显示它。
【问题讨论】:
我正在使用 Vue,但 我没有使用 vue-router。
如何获取 URI 参数?
我找到了一种使用 root el 属性获取 URI 的方法。
但是有什么合适的方法来获取我想要发送的参数 后端并从服务器获取响应并显示它。
【问题讨论】:
由于您没有使用vue-router,我认为您将无法访问您的参数。因此,您唯一的机会是将 URL api 用作:
const URL = new URL(window.location.href);
const getParam = URL.searchParams.get('foo');
这将为您提供?foo=bar 中 foo 的值
或者,你可以做这样的事情。
new Vue({
el: '#app',
data () {
return {
params: window.location.href.substr(window.location.href.indexOf('?'))
}
},
methods: {
getParam (p) {
let param = new URLSearchParams(this.params);
if(param.has(p)){
return param.get(p)
}else{
false
}
}
},
})
现在,只需使用 getParam('foo') 获取参数
【讨论】:
可以通过window.location.search获取URL参数:
const queryString = window.location.search;
console.log(queryString);
// ?product=troussers&color=black&newuser&size=s
查询字符串的解析参数,使用URLSearchParams:
const urlParams = new URLSearchParams(queryString);
欲了解更多信息,请阅读此tutorial。
【讨论】:
我们暂时也不使用 vue 路由器。我们使用以下脚本来解析 args。
var args = {};
var argString = window.location.hash;
//everything after src belongs as part of the url, not to be parsed
var argsAndSrc = argString.split(/src=/);
args["src"] = argsAndSrc[1];
//everything before src is args for this page.
var argArray = argsAndSrc[0].split("?");
for (var i = 0; i < argArray.length; i++) {
var nameVal = argArray[i].split("=");
//strip the hash
if (i == 0) {
var name = nameVal[0];
nameVal[0] = name.slice(1);
}
args[nameVal[0]] = decodeURI(nameVal[1]);
}
【讨论】:
路由属性存在于this.$route。
this.$router 是路由器对象的实例,它给出了路由器的配置。
您可以使用 this.$route.query 获取当前路由查询
【讨论】: