背景
在日常开发的时候,遇到需要根据输入框输入的url解析,出固定的一些字段展示在页面中,且这些解析出的值可以进行编辑并去改变原先的url生成新的url。
了解url
找到篇很详细的文章,虽然没怎么看懂 mp.weixin.qq.com/s?__biz=MjM…
功能实现
直接在vue的watch内写一个监听解析url
watch: {
'params.url': {
handler(val) {
if (val) {
this.url = new URL(val);
this.params['pin'] = this.url.searchParams.get('pin');
this.params['id'] = this.url.searchParams.get('id');
} else {
this.params['pin'] = '';
this.params['id'] = '';
}
}
}
}
这样就解析出来了想要的两个字段。
给展示字段的input框绑定input事件去实时修改url,拼接成新的url
@on-input="changeUrl('id', $event)" //绑定事件
// 拼接成新的url
changeUrl(str, value) {
if (this.url) {
this.url.searchParams.set(str, value);
let searchStr = this.url.searchParams.toString()
searchStr = decodeURIComponent(searchStr); // 对查询参数进行编码
this.params.url = `${this.url.origin}${this.url.pathname}?${searchStr}`
}
}
踩的坑
拼接新url的时候没有对查询参数进行编码,导致一些特殊的url修改以后会乱码没法用,加上这行代码就行了searchStr = decodeURIComponent(searchStr); // 对查询参数进行编码。
例如:www.baidu.com/debug/?http…
这样的url不进行编码直接修改会因为原先url内有 冒号,斜杠之类的会出现乱码。