vue.js - 有没有办法在 vuejs 路由器中加载动态组件..?
问题描述
我正在开发一个项目,可以根据特定条件使用多个主题/布局。我有一个仪表板面板,有 5 个 5 个预建主题,管理员一次可以选择某个主题,并基于该部分显示前端视图,假设管理员选择 ThemeOne,则路由器将仅使用 ThemeOne 组件,
路由.js
const selectedTheme = 'themeTwo'
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/'+ selectedTheme + '/Home.vue'
import About from './views/'+ selectedTheme + '/About.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
component: About
}
]
})
请帮忙...像这样
解决方案
- 您可以通过延迟加载来做到这一点:
...
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: () => import('./views/'+ selectedTheme + '/Home.vue')
},
{
path: '/about',
name: 'about',
component: () => import('./views/'+ selectedTheme + '/About.vue')
}
]
})
- 您也可以使用函数来选择组件:
...
function setComponanet(componentName){
return () => import('./views/'+ selectedTheme +'/'+ componentName +'.vue')
}
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: setComponanet('Home'))
},
{
path: '/about',
name: 'about',
component: setComponanet('About')
}
]
})
- 如果不想在导入中使用动态路径,可以在函数中使用 swtich
function setComponanet(componentName){
if(selectedTheme == themeOne)
{
switch(componentName){
case 'Home': return () => import('./view/themeOne/Home');
case 'About': return () => import('./view/themeOne/About');
default: return () => import('./view/themeOne/NotFount');
}
}
else if(selectedTheme == themeTwo)
{
switch(componentName){
case 'Home': return () => import('./view/themeTwo/Home');
case 'About': return () => import('./view/themeTwo/About');
default: return () => import('./view/themeTwo/NotFount');
}
}
}
- 动态路由的另一种方法是使用功能组件
...
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/:theme/:compName',
name: 'theme',
component: Theme
props: (route)=>({ selectedComp: route.params.theme + route.params.compName }) //selectedComp: themeOneHome
}
]
})
// in Theme.vue
import themeOneHome from './themeOne/Home'
import theOneAbout from './themeOne/About'
import themeTwoHome from './themeTwo/Home'
import theTwoAbout from './themeTwo/About'
const components = {
themeOneHome,
themeOneAbout,
themeTwoHome,
theTwoAbout
}
export default {
functional: true,
props: ['selectedComp'],
render(h, ctx) {
return h(components[ctx.props.selectedComp], ctx.data, ctx.children)
}
}
推荐阅读
- haskell - 在 Haskell 中调试内存问题
- selenium - 即使安装了 Selenium 也无法导入
- python-3.x - 如何防止箭头重叠?
- apache-kafka-connect - Debezium,Kafka-connect:对 postgres 的更新不会显示为消息,只有插入是
- groovy - 将值从子声明式 Jenkins 管道传递给父级
- c - 我在主进程和他的孩子之间共享 C 中的内存,但我无法同步他们的动作
- php - 通过 php 以编程方式获取 AWS Elastic Beanstalk 运行状况代码
- python - selenium 使用 python:如何正确单击()元素?
- c - 为什么我得到无穷大作为输出?你能找到程序中的错误吗?
- java - entityClass 在 AbstractGenericDao 中是如何工作的?