如何为Vue CLI多页应用配置user/:id格式的动态URL?
实现方案
vue-cli 的 pages 配置本身为静态多入口映射,无法直接支持动态路径参数匹配,你可以通过重写请求回退规则实现需求,具体步骤如下:
1. 修改vue.config.js配置
保留原有pages配置的基础上,新增devServer.historyApiFallback规则,让所有匹配/user/*的开发环境请求都落到user页面的入口上:
module.exports = { pages: { // 保留原有pages配置不变 'homepage': { entry: './src/pages/Homepage/main.js', template: 'public/index.html', title: 'Homepage', chunks: [ 'chunk-vendors', 'chunk-common', 'homepage' ] }, 'about': { entry: './src/pages/About/main.js', template: 'public/about.html', title: 'About', chunks: [ 'chunk-vendors', 'chunk-common', 'about' ] }, 'user': { entry: './src/pages/User/main.js', template: 'public/index.html', title: 'User', chunks: [ 'chunk-vendors', 'chunk-common', 'user' ] } }, // 新增开发环境重写规则 devServer: { historyApiFallback: { rewrites: [ // 所有/user/开头的路径都返回user页面对应的html { from: /^\/user\/.*$/, to: '/user.html' }, // 其他页面默认规则,按需保留 { from: /^\/about$/, to: '/about.html' }, { from: /^\/$/, to: '/index.html' } ] } } }
2. 页面内获取动态user id
user页面加载后可以通过两种方式拿到路径中的用户id参数:
- 如果user页面内部使用了vue-router,直接配置路由规则即可:
// user页面的路由配置 const router = new VueRouter({ mode: 'history', routes: [ { path: '/user/:id', component: UserComponent } ] }) // 代码中通过this.$route.params.id获取参数
- 如果没有使用路由,可以直接解析当前路径:
const userId = window.location.pathname.split('/')[2]
3. 生产环境适配
devServer配置仅对本地开发生效,部署到生产环境时需要额外配置服务端的重写规则,以Nginx为例,配置示例如下:
server { # 其他基础配置省略 location ^~ /user/ { try_files $uri $uri/ /user.html; } # 其他页面的规则按需配置 location /about { try_files $uri $uri/ /about.html; } location / { try_files $uri $uri/ /index.html; } }
如果使用其他部署服务,只要配置对应的规则,将所有/user/开头的请求都指向打包生成的user.html即可。
内容的提问来源于stack exchange,提问作者John Paul
相关产品推荐
相关产品推荐

