javascript - 基于路由的动态路由和组件创建
问题描述
我想为我的应用程序的部分提供几个“概述”页面,这些页面都将在该部分的根目录上触发。
所以localhost/hi
应该显示组件HiOverview
localhost/he
应该显示组件HeOverview
由于其中有多个,我想避免将组件分配给 const,然后在路由中重用它。相反,我想在一条动态路线中处理所有这些。
但是我正在努力在 beforeEnter 钩子中创建组件。每个route
对象都需要一个组件...但我只想根据路由来决定组件。(sectionsWithOverview
是一个简单的字符串数组,其中包含name
我想要显示概览的路线
const router = new Router({
linkActiveClass: 'active',
mode: 'history',
routes: [
{ path: '/:section',
component: Placeholder,
beforeEnter: (to, from, next) => {
const section = to.params.section
// how can i use this in the next() call?
// const View = () => import(/* webpackChunkName: 'sectionView' */ `Components/${section}/${section}Overview`)
if (sectionsWithOverview.includes(to.params.section)) {
next({ name: `${to.params.section}Overview` })
} else {
next()
}
},
}
你们能帮帮我吗?我如何有条件地分配一个组件 onBeforeEnter,然后路由到那个确切的组件?如果我SectionOverview
事先声明每一个,它就会起作用,但这会让我的整个想法变得毫无意义。
谢谢你的帮助 :)
解决方案
我在一个项目中做了类似的事情,但我使用了beforeRouteUpdate
这是它如何工作的示例。在 route.js 上简单地定义你的动态路由
const router = new Router({
linkActiveClass: 'active',
mode: 'history',
routes: [
{
path: '/:section',
component: Placeholder,
name: 'placeholder'
},
}
然后在您的 HTML 中的组件(我假设为 Placeholder.vue)中添加这行代码
<transition name="fade" mode="out-in">
<component :is="section" key="section"></component>
</transition>
然后在您的 JS 中添加beforeRouteUpdate
钩子并定义与您的路由部分参数匹配的所有组件。
import he from './heOverview.vue'
import hi from './hiOverview.vue'
beforeRouteUpdate (to, from, next) {
// just use `this`
this.section = to.params.section
next()
},
components: {
he,
hi
},
data () {
return {
section: ''
}
}
所以当用户导航到localhost/he
该heOverview.vue
组件时会被加载。您唯一需要确保的是,section
如果不会产生错误,参数的值应该与特定视图匹配
如果您需要有关此工作原理的更多信息,请阅读 https://vuejs.org/v2/guide/components-dynamic-async.html https://router.vuejs.org/guide/advanced/navigation-guards.html#组件内防护
推荐阅读
- android - 为什么Android允许未经许可读取文件?
- python - 如何在 XML 中获取特定根的数据(通过 python)
- cookies - 为什么 Chrome API 在 Firefox 中不起作用?
- reactjs - Webpack 工作箱插件 3.0 - 缓存附加文件(非 webpack 资产)
- javascript - 通过 Bot 框架中的后端通道发送位置详细信息
- android - 列别名引发错误:没有这样的列
- java - 当 url 包含分号时,在 Spring 5 中获得 500 响应
- postgresql - 如何遍历表并使用列属性在 postGIS 中创建一条线
- javascript - 通过包含函数的数组反向循环,没有jQuery
- docker - 使用 VSTS CI 将简单的 Java REST API 推送到 Docker 的步骤