HTML5 History 模式以及404页面的处理
课程来自 https://www.jspang.com
vue-router
默认使用 Hash 模式——使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8ydDx0PM-1586168468603)(D:\Document\JavaScript\Framework\Vue.js\Vue 复习笔记\Vue-router\HTML5 history模式1.png)]
如果不想要很丑的 hash,我们可以用陆游的 history 模式,这种模式充分利用 history.pushState
API 来完成 URL 跳转而无需重新加载页面。
import Vue from 'vue';
import Router from 'vue-router';
import Hello from '@/components/HelloWorld'
import Params from '@/components/Params';
import Hi1 from '../components/Hi1.vue';
Vue.use(Router);
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Hello',
component: Hello,
alias: '/home',
},
{
path: '/params/:newsId(\\d+)/:newsTitle',
component: Params,
},
{
path: '/gohome',
redirect: '/',
},
{
path: '/goparams/:newId(\\d+)/:newsTitle',
redirect: '/params/:newsId(\\d+)/:newsTitle'
},
{
path: '/hi1',
component: Hi1,
alias: '/qian',
}
]
})
但是,这么做的以后,你的服务器就不能再返回 404 错误页面,因为对于所有路径都会返回 index.html
文件。(上面的路由显示空白页面就是我个人网站的后端管理系统——虽然是用react做的但是由于使用的都是history模式结果应该相同,由于没有做进行处理404,当 url
地址错误时,出现的是一片空白)为了避免这种情况,你应该在 Vue 应用里面覆盖所有的路由情况,然后再给出一个 404 页面
import Vue from 'vue';
import Router from 'vue-router';
import Hello from '@/components/HelloWorld'
import Params from '@/components/Params';
import Hi1 from '@/components/Hi1.vue';
import Error from '@/components/404.vue';
Vue.use(Router);
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Hello',
component: Hello,
alias: '/home',
},
{
path: '*',
component: Error
}
]
})
404页面:
<template>
<div>
对不起,这个页面走失了
</div>
</template>
<script>
export default {
name: '404Page',
}
</script>
结果: