【发布时间】:2019-06-05 14:39:09
【问题描述】:
我们正在基于 Vue 和 Nuxt 构建一个庞大的网站,其中包含超过 25 种不同的页面类型,这些页面类型无法与 Vue Router 开箱即用的标准 /:id 或 /overview/:slug 逻辑匹配。
由于无法进行 slug 匹配,我们正在考虑以下解决方案:
- 用户访问页面“/this-is-a-topic-page”
- 服务器调用返回pageType
topicPage的API -
topicPage涉及到 nuxt 页面WpTopicPage - 我们将
WpTopicPage设置为 Vue 路由器通配符实例中的组件
这在代码中如下所示:
export function createRouter() {
return new Router({
mode: 'history',
routes: [
// 1. User visits page "/this-is-a-topic-page"
{
name: 'wildcard',
path: '*',
component: *, // this should be dynamic
beforeEnter: (to, from, next) => {
// 2. Server calls API that returns the pageType `topicPage`
this.$axios.get(`/call-to-the-api?slug=${to.params.slug}`)
.then((res) => {
// 3. `topicPage` relates to the nuxt page `WpTopicPage`
if(res.data.pageType === 'topicPage') {
// 4. Set `WpTopicPage` as our Page component
return WpTopicPage;
}
})
},
},
],
});
}
以上显然行不通。有没有办法在 beforeEnter 函数中动态设置路由内的component?
【问题讨论】:
-
也许Async Components 可以提供帮助
-
或者你可以使用Dynamic Components
-
@ljubadr。这是路由器实例,而不是组件。动态组件可以工作(我们目前有),但缺点是您渲染一个页面(它具有 Nuxt 的优势,如异步 Fetch 或 asyncData),它会切换一个动态组件。这意味着我们无法获取特定于页面的存储,因为动态组件不是 Nuxt Page 实例,而是实际组件。
标签: vue.js vue-router nuxt.js