url技巧
url相关转换
二进制转换url
- URL.createObjectURL(blob)
释放url对象
- URL.revokeObjectURL(url)
为什么需要释放url?
- 性能优化问题
- 可以释放内存
- 每次调用createObjectURL的时候,一个新的URL对象就被创建了,会占用浏览器内存
- 当不再需要这个对象,要释放它,需要使用URL.revokeObjectURL()方法
- 当页面被关闭,浏览器会自动释放它,但是为了最佳性能和内存使用,当确保不再用得到它的时候,就应该释放它
场景
- 比如文件下载场景,通过创建url给到a标签链接,来进行下载,完成下载时,就需要释放url
url操作
更新URL但不刷新
window.history.replaceState({}, '', url); // 更新URL但不刷新
设置url参数
const url = new URL(window.location.href);
url.searchParams.set('id', '2'); // 修改参数
url操作,vue hooks示例
- url获取,需要考虑hash、histroy路由问题
/*
* Vue 3 composable for unified URL operations (get/set/remove query parameters)
* Supports both History and Hash mode
* Usage:
* const { getParam, setParam, removeParam } = useUrlParams();
* getParam('key');
* setParam('key', 'value');
*/
export function useUrlParams() {
function isHashMode() {
const hash = window.location.hash;
return hash.startsWith('#/') || hash.includes('?');
}
/**
const urlSearch = new URLSearchParams('?aa=2&bb=3')
urlSearch.get('aa') => 2
*/
function parseParams(queryString) {
if (!queryString) return new URLSearchParams();
const qs = queryString.startsWith('?') ? queryString : `?${queryString}`;
return new URLSearchParams(qs);
}
/**
const url = new URL('https://demo.com/#/system/user?aa=2&bb=3')
url.hash => '#/system/user?aa=2&bb=3'
url.hash.slice(1).split('?') => ['/system/user', 'aa=2&bb=3']
*/
function getContext() {
if (isHashMode()) {
// https://demo.com/#/system/user?aa=2&bb=3
//
const [path, qs = ''] = window.location.hash.slice(1).split('?');
return {
mode: 'hash',
base: path || '',
params: parseParams(qs)
};
} else {
const path = window.location.pathname + window.location.search;
const qs = window.location.search;
return {
mode: 'history',
base: window.location.pathname,
params: parseParams(qs)
};
}
}
function getParam(key) {
const { params } = getContext();
return params.has(key) ? params.get(key) : null;
}
function setParam(key, value, options = {}) {
const { replace = false, title = document.title } = options;
const ctx = getContext();
ctx.params.set(key, value);
const newQuery = ctx.params.toString();
let newUrl;
if (ctx.mode === 'hash') {
newUrl = `#${ctx.base}${newQuery ? '?' + newQuery : ''}`;
} else {
newUrl = `${ctx.base}${newQuery ? '?' + newQuery : ''}`;
}
const method = replace ? 'replaceState' : 'pushState';
window.history[method]({}, title, newUrl);
}
function removeParam(key, options = {}) {
const { replace = false, title = document.title } = options;
const ctx = getContext();
ctx.params.delete(key);
const newQuery = ctx.params.toString();
let newUrl;
if (ctx.mode === 'hash') {
newUrl = `#${ctx.base}${newQuery ? '?' + newQuery : ''}`;
} else {
newUrl = `${ctx.base}${newQuery ? '?' + newQuery : ''}`;
}
const method = replace ? 'replaceState' : 'pushState';
window.history[method]({}, title, newUrl);
}
return {
getParam,
setParam,
removeParam
};
}