尝试使用v-on:blur使上下文菜单消失...但是它不起作用

Bén*_*uge 3 html onblur vue.js

我正在vue.js中编写一个简单的上下文菜单。当我右键单击一个特殊元素时,它会打开菜单(使用@ contextmenu.prevent)。

但是,当我在菜单外单击时,我希望它消失。这不起作用...我正在使用v-on:blur,也尝试了@blur。他们都没有用。这是我的html:

<!-- my context menu -->
<ul class="context-menu"
    ref="contextMenuTrack"
    v-if="openedMenu === 'contextMenuTrack'"
    v-bind:style="{top: top, left: left}"
    v-on:blur="closeMenu()">
    <li v-on:click="removeTrack(project.structure.tracks.indexOf(targetOfMenu));closeMenu()">delete track</li>
</ul>
<div>

    [ ...... stuff here ......]

    <!-- Where the menu is called-->
    <li class="track"
         v-for="track in project.structure.tracks">
        <div class="track-name-row">
            <li @contextmenu.prevent="openContextMenuTrack(track,$event)"
                v-on:click="expandTrack(project.structure.tracks.indexOf(track))"
                class="track-color-viewer"></li>

                [ .... other li tags .....]
        </div>
    </li>

    [ ...... stuff here ......]

</div>
Run Code Online (Sandbox Code Playgroud)

以下是用于Vue组件菜单的数据:

data() {
    return {
        //the kind of menu which is opened
        openedMenu: undefined,
        //the coordinate of the menu
        top: "0px",
        left: "0px",
        //the element which is targeted by the menu
        targetOfMenu: undefined
    };
},
Run Code Online (Sandbox Code Playgroud)

这是我的Vue.js组件中用于菜单的方法:

 methods: {

    setMenu(top, left) {
        this.top = top - 170 + "px";
        this.left = left + "px";
    },

    // opening menu : calling set menu whith x and y
    openContextMenuTrack(track, event) {
        this.openedMenu = "contextMenuTrack";
        this.targetOfMenu = track;

        this.$nextTick((() => {
            this.$refs.contextMenuTrack.focus();
            this.setMenu(event.y, event.x);
        }).bind(this));
    },

    closeMenu() {
        this.openedMenu = undefined;
        this.targetOfMenu = undefined;
    }
}
Run Code Online (Sandbox Code Playgroud)

Lin*_*org 6

blur事件仅存在于表单控件(<input>等)中。

通常,您可以通过创建一个自定义指令来解决您的问题,该自定义指令在您单击菜单外时会运行一个方法。

像这样:

https://www.npmjs.com/package/v-click-outside

<ul class="context-menu"
    ref="contextMenuTrack"
    v-if="openedMenu === 'contextMenuTrack'"
    v-bind:style="{top: top, left: left}"

    v-click-outside="closeMenu()">

    <li v-on:click="removeTrack(project.structure.tracks.indexOf(targetOfMenu));closeMenu()">delete track</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助

编辑:

带有更好包装的示例(vue-clickaway):

https://jsfiddle.net/Linusborg/hqkgp4hm/