需要做页面跳转的背景:
公司做的是后台系统,用的模板是eladmin后台,(自己摸索的)这个模板的路由采用的方式是前端在网页的菜单设置上自定义配置路由参数(包括如访问路径等),能够动态的生成路由,在内部js中实现将路由地址发送到后端,后端再返回路由menu,再通过内部js加载到前端的路由代码中。
问题:1、通过网页的菜单自定义配置路由参数,只能配置侧边栏的路由,而如在其他组件中设置子路由,来实现在父组件中的子组件跳转,就无法实现。猜测原因可能是搭框架的人把这部分功能删了,因为在eladmin体验版中,看到可以通过网页来进行设置父子路由
解决:尝试用以下几种办法来做,
其中第一种方法通过vue-router在代码中去配置父子路由,还未研究透彻。
v-show在组件内容不多时,用来做还是可以的,因为相当于是在同一个页面,所以也能看似达到了页面跳转后的缓存效果。缺点在于组件多的是后,单页面内容会过多,消耗内存
component动态组件加组件的按需加载,是最新在网上看到的,也是感觉最适合目前我的需求的方法。
这里主要讲第3种方法,第1种我没研究透,第2种太简单了,会用到的高级点的东西,也就是父子组件的传参或者通过vuex来传参
1、通过路由vue-router来实现
2、通过v-show来实现
3、通过component动态组件加载来实现
例子:
假设有以下三个组件:com1、com2、com3,有一个外层路/coms中代码如下
1 <template>
2 <div class="container">
3 <component :is="activeItem"/>
4 <button @click="changeActiveItem">切换</button>
5 </div>
6 </template>
7 <script>
8 export default {
9 name:"coms",
10 data(){
11 return {
12 activeItem:'com1'
13 }
14 },
15 components:{ //这里用的是按需导入组件
16 com1:()=>import('@/components/com-1.vue'),
17 com2:()=>import('@/components/com-2.vue'),
18 com3:()=>import('@/components/com-3.vue'),
19 },
20 methods:{
21 changeActiveItem(){
22 this.activeItem = this.activeItem === 'com1' ?
23 'com2' : this.activeItem === 'com2' ?
24 'com3' : 'com1'
25 }
26 }
27 }
28 </script>
另外一种场景:
需要在某个页面展示不确定数量的组件,具体展示什么组件由权限判断后后端返回一个数组。
1 <template>
2 <div class="container">
3 <component :is="item" v-for="item in allComponents" :key="item" />
4 </div>
5 </template>
6 <script>
7 export default {
8 name:"coms",
9 data(){
10 return {
11 allComponents:['com1','com2']
12 }
13 },
14 components:{
15 com1:()=>import('@/components/com-1.vue'),
16 com2:()=>import('@/components/com-2.vue'),
17 com3:()=>import('@/components/com-3.vue'),
18 }
19 }
20 </script>