本文将在vue+element ui项目中简单实现menu菜单的懒加载。
最近接到这样的需求:菜单的选项不要固定的,而是下一级菜单选项需要根据上级菜单调接口来获取。what? 这不就是懒加载吗?翻了一遍element ui文档,并没有找到menu菜单的懒加载,于是乎就自己手写一个啦。
首先最外层,子菜单打开的触发方式为click,用于之后点击调接口:
1 <el-menu class="el-menu-demo" mode="horizontal" @select="handleSelect" menu-trigger="click" unique-opened>...</el-menu>
内部具体实现:
html:
1 ...
2
3 <el-submenu v-if="business == 3" index="1-1-2" class="bgkh" @click.native="clickSub('1-1-2')">
4 <template slot="title">致函客户—中文</template>
5 <el-menu-item index="loading" v-if="loading">加载中...</el-menu-item>
6 <el-menu-item index="noData" v-if="noData">无数据</el-menu-item>
7 <el-submenu :index="`1-1-2-1-${index}`" v-for="(item,index) in jieduanList" :key="index" @click.native="queryMailTypeAll(1,item.jieduan)">
8 <template slot="title">{{item.jieduan}}</template>
9 <el-menu-item index="nextLoading" v-if="nextLoading">加载中...</el-menu-item>
10 <el-menu-item index="nextNoData" v-if="nextNoData">无数据</el-menu-item>
11 <el-menu-item :index="`1-1-2-1-${index}-${ind}`" v-for="(it,ind) in mailTypeAllList">{{it.mailTypeDesc}}</el-menu-item>
12 </el-submenu>
13 </el-submenu>
14
15 ...
js:
1 ...
2
3 queryMailTypeAll(businessType,jieduan){
4 this.nextLoading = true
5 this.nextNoData = false
6 this.mailTypeAllList = []
7 queryMailTypeAll({
8 businessType,
9 jieduan,
10 caseIds:this.multipleSelection.map(item=>item.caseId)
11 }).then(res=>{
12 this.nextLoading = false
13 this.mailTypeAllList = res.data.filter(item=>!!item)
14 this.mailTypeAllList&&!this.mailTypeAllList.length&&(this.nextNoData = true)
15 }).catch(err=>{
16 this.mailTypeAllList = []
17 this.nextLoading = false
18 this.nextNoData = true
19 })
20 },
21 queryJieduan(businessType){
22 this.loading = true
23 this.noData = false
24 this.jieduanList = []
25 queryJieduan({
26 caseIds:this.multipleSelection.map(item=>item.caseId),
27 businessType
28 }).then(res=>{
29 this.loading = false
30 this.jieduanList = res.data.filter(item=>!!item)
31 this.jieduanList&&!this.jieduanList.length&&(this.noData = true)
32 }).catch(err=>{
33 this.jieduanList = []
34 this.loading = false
35 this.noData = true
36 })
37 },
38 clickSub(key){
39 this.business == 3 && key == '1-1-2' && (this.queryJieduan(1))
40 this.business == 3 && key == '1-1-3' && (this.queryJieduan(2))
41 }
42
43 ...
最后效果图:
完事儿收工,简易的模拟懒加载效果实现啦!此写法为最初版本,还可以根据业务需求进行更深层次的封装达到复用。