element-ui el-tree 右键菜单实现

直接上代码:

 <div
            id="rightMenu"
            v-if="visible"
            class="tree_menu"
            :style="rightMenuStyle"
            :key="(currentNode && currentNode.id) || '0'" 
        >
            <ul>
                <li v-if="addTypeLi" @click="addType">
                    <i class="el-icon-circle-plus-outline"></i> 添加
                </li>
                <li @click="renameType"><i class="el-icon-edit"></i> 重命名</li>
                <li @click="delType"><i class="el-icon-delete"></i> 删除</li>
            </ul>
        </div>
注意

key不能少,否则rightMenu不更新位置

    getContextmenu(e, data) {
            this.rightMenuStyle =
                "top:" + e.pageY + "px; left:" + e.pageX + "px";
            this.visible = true;
            this.currentNode = data;
            if (data.children && data.children.length > 0) {
                this.addTypeLi = true;
            } else {
                this.addTypeLi = false;
            }
            const self = this;
            document.onclick = function (ev) {
                if (ev.target !== document.getElementById("rightMenu")) {
                    self.visible = false;
                }
            };
        },
      // 解决单击隐藏右键菜单的问题
       handleNodeClick(data, node) {
            if (this.visible) {
                this.visible = false;
            }
        }

css

.tree_menu {
        position: absolute;
        background-color: #fff;
        padding: 5px 0;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

        ul {
            margin: 0;
            padding: 0;
        }
        ul li {
            list-style: none;
            margin: 0;
            padding: 0 15px;
            font-size: 14px;
            line-height: 30px;
            cursor: pointer;
        }
        ul li:hover {
            background-color: #ebeef5;
        }
    }

本文章由javascript技术分享原创和收集

发表评论 (审核通过后显示评论):