常见问题:
- history 和 hash 模式的区别是什么?(涉及路由模式和前端发布原理)
- Vue dev 模式下为什么不需要配置 history fallback ?(涉及 webpack-dev-server 配置)
- 明明没有定义router-link和router-view,为什么代码里能直接使用? (涉及vue-router初始化流程和 Vue插件)
- 浏览器中如何实现 URL 变化但页面不刷新? (涉及 vue-router history模式核心实现原理)
- vue-router 如何实现路由匹配? (涉及 vue-router Matcher 实现原理)
- router-view 如何实现组件动态渲染? (涉及 Vue 动态组件)
vue-router 路由模式
官网地址 hash 和 history 模式区别:语法结构不同,部署方式不同;SEO 。 history 修改 URL 时会请求加载新的资源,而 hash 没有,会导致在实际部署上产生不用的效果,另外 hash 对 SEO 不友好,hash 值变化时前面的路径资源一直不变,不利于爬虫引擎搜索。 history 模式部署常见的问题:输入 /
可以访问 /home
页,点击其他链接可以跳转, 而直接输入 /order
就出现 404,为什么?原因是路径的资源映射,/
映射的是 index.html
,而 /order
没有对应的资源进行映射,所以会返回 404 页面。 解决方案是:对
Nginx
进行配置。
nginx
location / {
try_files $uri $uri/ /index.html;
}
vue create server 中不配置 history fallback 的原因
因为 vue create server
使用到 webpack-dev-server
, 重写了 rewrites
。
js
new WebpackDevServer(compiler, {
historyApiFallback: {
disabledDotRule: true,
rewrites: genHistoryApiFallbackRewrites(
options.publicPath,
options.pages
)
}
})
// genHistoryApiFallbackRewrites 返回值
return [
...multiPageRewrites,
{
from: /./,
to: path.posix.join(baseUrl, 'index.html')
}
]