我在 vue router 中的一条路由需要一个带有 ID 的 prop,所以我添加了一个。
const routes = [
{
path: '/user/:id',
name: 'user',
component: UserProfile,
props: true
},
//...
]
在开发过程中,我使用了 WebHashHistoryMode,因为它更简单并且 props 正在工作。然而,对于构建,我将其切换为 WebHistoryMode 并使用“更好的”url:
const router = createRouter({
history: createWebHistory(),
routes,
scrollBehavior() {
return { top: 0 }
},
})
然后我快速准备了一个带有express.js的app.js文件,用于处理节点应用程序的后备(这不是我的第一个vue项目,我知道它以前可以工作):
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
const port = process.env.PORT || 443;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
工作起来就像一个魅力,但是当访问 /user/id 页面时,我只得到一个空白页面。看起来像 / 之前的“用户”被视为文件夹,而不是带有 prop 的页面。我该如何修复它,将 /user/id 重定向到 index.html,当然还要传递 id 属性?
提前致谢
我找到了一个解决方案,或者更像是一个解决方法。我将声明的路线更改为“功能模式”,因此道具通过查询传递。
const routes = [
{
path: '/user',
name: 'user',
component: UserProfile,
props: route => ({ id: route.query.id })
},
//....
]
现在网址看起来像 example.com/user?id=10 而不是 example.com/user/10。 这不是最好看的网址,但它可以解决问题。
但是,如果你们中有人知道如何解决这个问题,请随时写信。