element+vue鼠標右鍵顯示菜單

<template>
    <el-container style="height: 630px">
        <el-aside width="300px">
            <el-tree :data="productTypes" :props="defaultProps" node-key="id"
                     @node-contextmenu="rightClick" @node-click="handlClick">
            </el-tree>
            <div v-show="menuVisible">
                <ul id="menu" class="menu">
                    <li class="menu_item" @click="">平級添加</li>
                    <li class="menu_item" @click="">下級添加</li>
                    <li class="menu_item" @click="">刪除</li>
                </ul>
            </div>
        </el-aside>
        <el-main>
        </el-main>
    </el-container>
</template>

<script>
    export default {
        data() {
            return {
                menuVisible: false,
                productTypes: [],
                defaultProps: {
                    children: 'children',
                    label: 'name'
                }
            }
        },
        methods: {
            //加載樹的數據
            loadTreeData() {
                this.$http.get("/product/productType/tree").then((res) => {
                    this.productTypes = res.data;
                })
            },
            handlClick() {
            },
            //右鍵點擊
            rightClick(MouseEvent, object, Node, element) { // 鼠標右擊觸發事件
                this.menuVisible = false // 先把模態框關死,目的是 第二次或者第n次右鍵鼠標的時候 它默認的是true
                this.menuVisible = true  // 顯示模態窗口,跳出自定義菜單欄
                var menu = document.querySelector('#menu')
                document.addEventListener('click', this.foo) // 給整個document添加監聽鼠標事件,點擊任何位置執行foo方法
                menu.style.display = "block";
                menu.style.left = MouseEvent.clientX - 0 + 'px'
                menu.style.top = MouseEvent.clientY - 80 + 'px'
            },
            foo() { // 取消鼠標監聽事件 菜單欄
                this.menuVisible = false
                document.removeEventListener('click', this.foo) // 要及時關掉監聽,不關掉的是一個坑,不信你試試,雖然前臺顯示的時候沒有啥毛病,加一個alert你就知道了
            },
        },
        mounted() {
            this.loadTreeData();
        }
    }
</script>

<style scoped>
    .el-aside {
        border: 1px solid #ccc;
        border-right: none;
    }

    .el-main {
        border: 1px solid #ccc;
    }

    .menu_item {
        line-height: 20px;
        text-align: center;
        margin-top: 10px;
    }

    .menu {
        height: 100px;
        width: 80px;
        position: absolute;
        border-radius: 10px;
        border: 1px solid #999999;
        background-color: #f4f4f4;
    }

    li:hover {
        background-color: #1790ff;
        color: white;
    }
    li{font-size:15px}
</style>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章