admin管理员组文章数量:1633915
无法实现多页面多路由的源码分析
createWebHistory和createWebHashHistory的区别
首先是createWebHistory
/**
* Creates an HTML5 history. Most common history for single page applications.
* single page applications: 只能在单页面的范畴使用
* @param base -
*/
function createWebHistory(base) {
base = normalizeBase(base); //问题就出现在这里
const historyNavigation = useHistoryStateNavigation(base);
const historyListeners = useHistoryListeners(base, historyNavigation.state, historyNavigation.location, historyNavigation.replace);
function go(delta, triggerListeners = true) {
if (!triggerListeners)
historyListeners.pauseListeners();
history.go(delta);
}
进入normalizeBase()方法
/**
* Normalizes a base by removing any trailing slash and reading the base tag if
* present.
*
* @param base - base to normalize
*
*/
function normalizeBase(base) {
if (!base) { //这里就开始判断是否存在base参数,如果有直接跳到else!!!!!!!!
/*这里的目的是,防止页面url输入不符合路由的路径, 直接返回默认首页,解决404问题*/
if (isBrowser) {//这里就开始判断是否在window上,
// respect <base> tag
const baseEl = document.querySelector('base');
base = (baseEl && baseEl.getAttribute('href')) || '/'; //这就是我的猜测了, 获取base对象, 进行判断获取href参数是否存在在路由中,如果不存在的话,直接返回默认根路径"/"
// strip full URL origin
base = base.replace(/^\w+:\/\/[^\/]+/, ''); //清空url的参数
}
else {
base = '/'; //这里会直接变成vite2配置的默认index.html路径
}
}
补充一下:
表达式a && 表达式b : 计算表达式a(也可以是函数)的运算结果,
如果为 True, 执行表达式b(或函数),并返回b的结果;
如果为 False,返回a的结果;
表达式a || 表达式b : 计算表达式a(也可以是函数)的运算结果,
如果为 Fasle, 执行表达式b(或函数),并返回b的结果;
如果为 True,返回a的结果;
对象为true;
非零数字为true;
零为false;
非空字符串为true;
空字符串为法false;
其他为false;
createWebHashHistory
Params:
base – optional base to provide. Defaults to location.pathname + location.search If there is a <base> tag in the head, its value will be ignored in favor of this parameter but note it affects all the history.pushState() calls, meaning that if you use a <base> tag, it's href value has to match this parameter (ignoring anything after the #).
//这里的意思很明确了,就是以可设置的指定页面为作为入口,进行组件加载, 所以刷新F5或Ctrl+F5刷新不会出现问题
function createWebHashHistory(base) {
// Make sure this implementation is fine in terms of encoding, specially for IE11
// for `file://`, directly use the pathname and ignore the base
// location.pathname contains an initial `/` even at the root: `https://example`
base = location.host ? base || location.pathname + location.search : '';
// allow the user to provide a `#` in the middle: `/base/#/app`
if (!base.includes('#'))
base += '#';
if ((process.env.NODE_ENV !== 'production') && !base.endsWith('#/') && !base.endsWith('#')) {
warn(`A hash base must end with a "#":\n"${base}" should be "${base.replace(/#.*$/, '#')}".`);
}
return createWebHistory(base);
}
个人猜测, 希望大佬多多指正!
版权声明:本文标题:vue3+vite2多页面多路由 注意 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1729176860a1188828.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论