前言:
心情不好,废话太多,简而言之就是使用 window.history.replaceState 达到url值更新而不再刷新页面!不想看吐槽可以不用往下看。
公司vue项目中使用路由的hash模式,在项目部署到服务器后出现一个没涉及过的疑点;正常来说,项目部署后访问项目地址应该是 http://ip:port/项目名/index.html 然后按回车加载内容页面地址变成http://ip:port/项目名/index.html#/?query=123这里路径只是举个栗子!!但是不知道项目部署后访问 http://ip:port/dist1/ 然后按回车页面地址变成 http://ip:port/dist1/#/?query=123 可以正常加载内容且加载内容和带index.html的内容一样。
疑点还没搞明白为什么;有知道的可以告知下原因,万分感谢!!!
项目中,不是通过路由修改的URL地址,是通过window.location.href 获取URL然后手动进行修改的 (项目中尽量不要使用这种方式,最好使用路由!!!)
updateLocationURL(word){
//word是输入框中输入的内容
let newURL = window.location.href
if(newURL.indexOf("?")!=-1){
let newhttp = newURL.substr(0,newURL.indexOf("?") + 1)
let lasthttp = newhttp + 'query=' + word
window.location.href = lasthttp
}else{
let lasthttp = newURL + '/?query=' + word
window.location.href = lasthttp
}
}
到这里问题才开始,领导奇思妙想的需求:http://ip:port/dist1/#/?query=123 为啥路径中要带#号(在这里解释了路由的两种模式);但是人家就是不管,提出如果客户非要把#号给删除掉,然后问题来了!http://ip:port/dist1/#/?query=123 把 “#/” 删掉然后回车,路径变成了 http://ip:port/dist1/?query=123#/ 导致项目导航栏功能失效(这是的updateLocationURL函数的参数word的值是 123#/)!建议领导不使用hash模式改成history模式,但是后端不给配合改nginx配置。然后就有新想法,把参数后面的#移除然后放在本该在的位置,结果导致页面会刷新两次。为了客户体验效果,想到了使用 window.history.replaceState 控制改变url但不刷新页面
setnewhref(word) {
// console.log(word.split('#/')[0], "搜索词");
word = word.split("#/")[0];
//设置新的页面地址
let nowurl = window.location.href;
if (nowurl.indexOf("?") != -1) {
let nowhttp = nowurl.substr(0, nowurl.indexOf("?") + 1); //网址?号前的字符
/*
* http://192.168.1.149:8080/#/? http://192.168.1.149:8080/? (本地)
*
* http://221.237.109.120.28100/dist1/#/?
* http://221.237.109.120:28100/dist1/?
*/
let temphttp = nowhttp.split("?")[0];
if (temphttp.indexOf("#") == -1) {
//不包含'#'
temphttp = temphttp + "#/";
}
nowhttp = temphttp + "?";
let newhttp = nowhttp + "query=" + word;
// window.location.href = newhttp; //设置新的网页地址
window.history.replaceState(null, "", newhttp); //设置新的网页地址但不刷新页面
} else {
let newhttp = nowurl + "/?query=" + word;
window.location.href = newhttp;
}
},