我无法通过 Vue 解决这个问题,但是,tao提到过,这可能是 GitHub 及其处理 URL 的方式的问题。最简单的解决方法是使用哈希路由器,以便条目 URL 保持静态。然而,这会引入,可以说是令人厌恶的/#/
在您的网址中。
鉴于本机不支持包罗万象的路由,有人找到了解决方法:https://github.com/rafgraph/spa-github-pages. Note:这可能不利于 SEO,因为预期的 URL 实际上并不存在。这是利用 404 重定向并在索引页面上处理它的技巧。这是一个投资组合网站,因此,我现在对此表示同意。如果我或其他人找到更好的解决方案,将会更新。
解决方法:
Inside /public
添加一个名为404.html
并粘贴以下内容:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CHANGE THIS TO YOUR TITLE</title>
<script type="text/javascript">
// MIT License
// https://github.com/rafgraph/spa-github-pages
// This script takes the current url and converts the path and query
// string into just a query string, and then redirects the browser
// to the new url with only a query string and hash fragment,
// e.g. https://www.foo.tld/one/two?a=b&c=d#qwe, becomes
// https://www.foo.tld/?/one/two&a=b~and~c=d#qwe
// Note: this 404.html file must be at least 512 bytes for it to work
// with Internet Explorer (it is currently > 512 bytes)
// If you're creating a Project Pages site and NOT using a custom domain,
// then set pathSegmentsToKeep to 1 (enterprise users may need to set it to > 1).
// This way the code will only replace the route part of the path, and not
// the real directory in which the app resides, for example:
// https://username.github.io/repo-name/one/two?a=b&c=d#qwe becomes
// https://username.github.io/repo-name/?/one/two&a=b~and~c=d#qwe
// Otherwise, leave pathSegmentsToKeep as 0.
var pathSegmentsToKeep = 0;
var l = window.location;
l.replace(
l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
l.pathname.split('/').slice(0, 1 + pathSegmentsToKeep).join('/') + '/?/' +
l.pathname.slice(1).split('/').slice(pathSegmentsToKeep).join('/').replace(/&/g, '~and~') +
(l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
l.hash
);
</script>
</head>
<body>
</body>
</html>
Inside /public/index.html
,在里面添加以下内容<head>
就在之后<title>
:
<script type="text/javascript">
// MIT License
// https://github.com/rafgraph/spa-github-pages
// This script checks to see if a redirect is present in the query string,
// converts it back into the correct url and adds it to the
// browser's history using window.history.replaceState(...),
// which won't cause the browser to attempt to load the new url.
// When the single page app is loaded further down in this file,
// the correct url will be waiting in the browser's history for
// the single page app to route accordingly.
(function(l) {
if (l.search[1] === '/' ) {
var decoded = l.search.slice(1).split('&').map(function(s) {
return s.replace(/~and~/g, '&')
}).join('?');
window.history.replaceState(null, null,
l.pathname.slice(0, -1) + decoded + l.hash
);
}
}(window.location))
</script>
这对我有用,我现在只需输入即可访问联系人页面myname.com/contact
。如果您内部有嵌套 SPA,这也应该有效/public
,使用同样的技巧。