html - 尝试使用 v-on :blur for making disappear a context menu. ..但它不起作用

标签 html vue.js onblur

我正在用 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>

这是用于我的 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
    };
},

下面是我的 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;
    }
}

最佳答案

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>

希望对你有帮助

编辑:

一个更好的包的例子(vue-clickaway):

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

关于html - 尝试使用 v-on :blur for making disappear a context menu. ..但它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45838800/

相关文章:

javascript - 流过当前页面的页面

html - 如何在 Opera 中使用 css 居中 <img> html 标签?

node.js - 找不到页面 "/"路由

javascript - jQuery 查找 (':focus' ) 未按预期运行

javascript - 需要点击2次才能失去焦点

javascript - 覆盖模态窗体的宽度 MVC/C#

javascript - 谷歌地图自动完成 InvalidValueError : not an instance of HTMLInputElement

vue.js - VueJS 精确事件类

javascript - Vue i18N SAP 多语言最佳实践?

javascript - 如何防止 BLUR 事件多次触发?