Vue.js如何获取URL中/后的参数并赋值给this.searchQuery
从URL斜杠后提取参数并赋值给
this.searchQuery 核心实现思路
根据URL的结构,通过解析路径字符串提取目标内容,再赋值给变量。以下是针对不同URL场景的具体实现:
场景1:提取URL路径最后一段(如https://xxx.com/search/john中的john)
// 拆分路径并过滤空字符串(避免开头斜杠导致的空元素) const pathSegments = window.location.pathname.split('/').filter(seg => seg); // 取最后一段作为参数,为空时设默认值'' this.searchQuery = pathSegments[pathSegments.length - 1] || '';
场景2:提取指定位置的路径段(如https://xxx.com/user/john/profile中的john)
假设目标内容在第2个斜杠后(索引从0开始):
const pathSegments = window.location.pathname.split('/').filter(seg => seg); // 根据实际结构调整索引,这里取第1个非空段(对应路径中的john) this.searchQuery = pathSegments[1] || '';
结合你的现有代码修改
把参数提取逻辑放到mounted钩子中,确保在调用loadUsers前完成赋值:
mounted () { // 提取URL斜杠后的参数 const pathSegments = window.location.pathname.split('/').filter(seg => seg); this.searchQuery = pathSegments[pathSegments.length - 1] || ''; this.loadUsers(); }
可选:将参数传入接口请求
如果需要把searchQuery作为参数传给后端接口,修改loadUsers方法:
loadUsers(){ this.loading = true; // 用encodeURIComponent处理参数,避免特殊字符导致URL异常 const requestUrl = `${window.config.apiUrl}/widgets/search-users?userServices=false&query=${encodeURIComponent(this.searchQuery)}`; fetch(requestUrl) .then(res => res.json()) .then(response => { this.users = response.users; }) .catch(err => { console.log(err); }) .finally(() => (this.loading = false)); }
注意事项
window.location.pathname仅返回URL的路径部分(不包含域名和查询参数?xxx=xxx)- 必须用
filter(seg => seg)过滤拆分后产生的空字符串,避免索引错误 - 特殊字符参数要通过
encodeURIComponent转义,保证URL格式合法
内容的提问来源于stack exchange,提问作者nevergiveafuck
相关产品推荐
相关产品推荐

