为什么要动态渲染?
比如我们现在需要以下侧边栏的数据:
如果一个个的去写标签会很麻烦,发现导航栏中的数据分为两类,一类是一级导航,另一位是二级导航(有子页),因此直接写两个函数判断是否有子页,然后循环遍历所有的menudata(上图),直接显示
上图中的代码可以把这几个导航一级页全部展示出来,
完整的代码CommonAside
<template>
<div>
<el-menu default-active="1-4-1" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose"
:collapse="isCollapse">
<!--
<el-menu-item v-for="item in noChildren" :key="item.name" :index="item.name">
<i :class="`el-icon-${item.icon}`"></i>
<span slot="title">{{ item.label }}</span>
</el-menu-item>
-->
<el-menu-item v-for="item in noChildren" :key="item.name" :index="item.name">
<!-- i标签是图标 -->
<!-- 静态渲染 -->
<!-- <i :class="el-icon-menu"></i> -->
<!-- 动态渲染 -->
<!-- 导航的文字 -->
<span slot="title">{{item.label}}</span>
</el-menu-item>
<el-submenu index="1">
<template slot="title">
<i class="el-icon-location"></i>
<span slot="title">导航一</span>
</template>
<el-menu-item-group>
<el-menu-item index="1-1">选项1</el-menu-item>
<el-menu-item index="1-2">选项2</el-menu-item>
</el-menu-item-group>
</el-submenu>
</el-menu>
</div>
</template>
<style>
.el-menu-vertical-demo:not(.el-menu--collapse) {
width: 200px;
min-height: 400px;
}
</style>
<script>
export default {
data() {
return {
isCollapse: false,
menuData: [
{
path: '/',
name: 'home',
label: '首页',
icon: 's-home',
url: 'Home/Home'
},
{
path: '/mall',
name: 'mall',
label: '商品管理',
icon: 'video-play', //图标
url: 'MallManage/MallManage'
},
{
path: '/user',
name: 'user',
label: '用户管理',
icon: 'user',
url: 'UserManage/UserManage'
},
{
label: '其他',
icon: 'location',
children: [{
path: '/page1',
name: 'page1',
label: '页面1',
icon: 'setting',
url: 'Other/PageOne'
},
{
path: '/page2',
name: 'page2',
label: '页面2',
icon: 'setting',
url: 'Other/PageTwo'
}
]
}
]
};
},
methods: {
handleOpen(key, keyPath) {
console.log(key, keyPath);
},
handleClose(key, keyPath) {
console.log(key, keyPath);
}
},
computed:{
//无子菜单
noChildren() {
return this.menuData.filter(item => !item.children)
},
//有子菜单
hasChildren() {
this.menuData.filter(item => item.children)
}
},
}
</script>
重要部分:
<el-menu-item v-for="item in noChildren" :key="item.name" :index="item.name">
<!-- i标签是图标 -->
<!-- 静态渲染 -->
<!-- <i :class="el-icon-menu"></i> -->
<!-- 动态渲染 -->
<i :class="`el-icon-${item.icon}`"></i>
<!-- 导航的文字 -->
<span slot="title">{{item.label}}</span>
</el-menu-item>
computed:{
//无子菜单
noChildren() {
return this.menuData.filter(item => !item.children)
},
//有子菜单
hasChildren() {
this.menuData.filter(item => item.children)
}
},