关于element-ui 下拉菜单 el-dropdown-menu 组件 不能动态渲染 数据怎么解决?
element-ui 官网中的例子是这样写的
<el-dropdown>
<span class="el-dropdown-link">
下拉菜单<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>黄金糕</el-dropdown-item>
<el-dropdown-item>狮子头</el-dropdown-item>
<el-dropdown-item>螺蛳粉</el-dropdown-item>
<el-dropdown-item disabled>双皮奶</el-dropdown-item>
<el-dropdown-item divided>蚵仔煎</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<style>
.el-dropdown-link {
cursor: pointer;
color: #409EFF;
}
.el-icon-arrow-down {
font-size: 12px;
}
</style>
写法一
我一开始是这样写的,循环的是整个 el-dropdown-item 组件,
v-for语句写在了el-dropdown-menu 里,发现页面上只能渲染出列表中最后一个元素。
说明这种写法不能动态渲染数据
<template>
<div>
<el-dropdown trigger="click" >
<span class="el-dropdown-link" ref="ellink" >
{{ test_obj.title }}<i class="el-icon-arrow-down el-icon--right" />
</span>
<el-dropdown-menu slot="dropdown" align="center" v-for="item in test_obj.arr" :key="item.id">
<el-dropdown-item >
{{ item.desc }}
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</div>
</template>
<script>
export default {
name:'test',
data(){
return {
test_obj:{
title:'测试下拉菜单',
arr:[
{id:1,desc:'测试1'},
{id:2,desc:'测试2'},
{id:3,desc:'测试3'}
]
}
}
}
}
</script>
结果只显示列表中最后一个数据
写法二
换成以下写法,直接在 el-dropdown-item 组件里写v-for语句,发现可以动态渲染,满足我项目中的需求
<el-dropdown trigger="click" ref="eldrop">
<span class="el-dropdown-link" ref="ellink" >
{{ Global.default_department.name }}<i class="el-icon-arrow-down el-icon--right" />
</span>
<el-dropdown-menu slot="dropdown" align="center" >
<el-dropdown-item v-for="department in Global.departments" @click.native="getDepartment(department)" :key="department.id">
{{ department.name }}
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
查看了下两种写法渲染后的真实html内容如下
写法一的,只渲染最后一组的html
<ul class="el-dropdown-menu el-popper" align="center" id="dropdown-menu-3569" x-placement="bottom-end">
<li tabindex="-1" class="el-dropdown-menu__item">
测试1
</li>
<div x-arrow="" class="popper__arrow"></div>
</ul>
<ul class="el-dropdown-menu el-popper" align="center" id="dropdown-menu-3569" x-placement="bottom-end">
<li tabindex="-1" class="el-dropdown-menu__item">
测试2
</li>
<div x-arrow="" class="popper__arrow"></div>
</ul>
<ul class="el-dropdown-menu el-popper" align="center" id="dropdown-menu-3569" x-placement="bottom-end">
<li tabindex="-1" class="el-dropdown-menu__item">
测试3
</li>
<div x-arrow="" class="popper__arrow"></div>
</ul>
写法二的,正常渲染了的html
<ul class="el-dropdown-menu el-popper" align="center" id="dropdown-menu-3203" x-placement="bottom-end">
<li tabindex="-1" class="el-dropdown-menu__item">
测试A
</li>
<li tabindex="-1" class="el-dropdown-menu__item">
测试B
</li>
<li tabindex="-1" class="el-dropdown-menu__item">
测试C
</li>
<div x-arrow="" class="popper__arrow"></div>
</ul>
可以得出,写法二其实也渲染了三个li元素,但是位置重合了,根据z-index大小,只显示最后一个数据。
所以写下拉菜单时,只循环el-dropdown-item组件中的内容就可以正常动态渲染数据。