首页 > 解决方案 > 基于路由的动态路由和组件创建

问题描述

我想为我的应用程序的部分提供几个“概述”页面,这些页面都将在该部分的根目录上触发。

所以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事先声明每一个,它就会起作用,但这会让我的整个想法变得毫无意义。

谢谢你的帮助 :)

标签: javascriptvue.jsvue-router

解决方案


我在一个项目中做了类似的事情,但我使用了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/heheOverview.vue组件时会被加载。您唯一需要确保的是,section如果不会产生错误,参数的值应该与特定视图匹配

如果您需要有关此工作原理的更多信息,请阅读 https://vuejs.org/v2/guide/components-dynamic-async.html https://router.vuejs.org/guide/advanced/navigation-guards.html#组件内防护


推荐阅读