Vue路由History mode模式中页面无法渲染的原因及解决

来源:互联网 发布:网络语青铜是什么意思 编辑:程序博客网 时间:2024/05/22 07:00

Vue.js + vue-router 创建单页应用,是非常简单的。使用 Vue.js ,我们将组件(components)映射到路由(routes),然后告诉 vue-router 在哪里渲染它们。一般开发的单页应用的URL都会带有#号的hash模式,因为整个应用本身而言就只有一个HTML,其他的都是通过router来渲染。url带#号会带来很多bug,例如:微信分享和微信支付配置等传的url是不含#号的,那么可以使用history模式,简单而言就是在router的配置文件index.js中添加如下一行代码:

export default new Router({mode:"history",//此处添加routes: [ {path: '/error',name: 'error',component: require('../components/view/error'),meta: {title: '操作失败'}}]

404错误

在History mode下,如果直接通过地址栏访问路径,那么会出现404错误,这是因为这是单页应用(废话)…其实是因为调用了history.pushState API 所以所有的跳转之类的操作都是通过router来实现的,解决这个问题很简单,只需要在后台配置如果URL匹配不到任何静态资源,就跳转到默认的index.html。具体配置如下:

Apache

<IfModule mod_rewrite.c>  RewriteEngine On  RewriteBase /  RewriteRule ^index\.html$ - [L]  RewriteCond %{REQUEST_FILENAME} !-f  RewriteCond %{REQUEST_FILENAME} !-d  RewriteRule . /index.html [L]</IfModule>
nginx
location / {  try_files $uri $uri/ /index.html;}




阅读全文
1 0
原创粉丝点击