动态组件,让页面渲染更灵活

根据用户的权限不同,页面上要显示不同的内容
页面引入组件较多
如果逐个判断权限引入的话,v-if,v-else-if 使用太多,影响代码的美观

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<template>
<div class="info">
<component :is="roleComponent" v-if="roleComponent" />
</div>
</template>
<script>
import AdminInfo from "./admin-info";
import BookkeeperInfo from "./bookkeeper-info";
import HrInfo from "./hr-info";
import UserInfo from "./user-info";
export default {
components: {
AdminInfo,
BookkeeperInfo,
HrInfo,
UserInfo
},
data() {
return {
roleComponents: {
admin: AdminInfo,
bookkeeper: BookkeeperInfo,
hr: HrInfo,
user: UserInfo
},
role: "user",
roleComponent: undefined
};
},
created() {
const { role, roleComponents } = this;
this.roleComponent = roleComponents[role];
}
};
</script>