简体   繁体   English

单击文档上任何位置时,隐藏弹出框

[英]Hide popup box when clicked anywhere on the document

I am trying to make a component with a list of items and when I click on each of the items, it shows me an edit popup. 我正在尝试制作一个带有项目列表的组件,当我单击每个项目时,它会显示一个编辑弹出窗口。 When I click on it again, it hides the edit popup. 当我再次单击它时,它会隐藏编辑弹出窗口。 But I would like to also be able to click anywhere on the document and hide all edit popups (by setting edit_item_visible = false). 但我也希望能够单击文档上的任意位置并隐藏所有编辑弹出窗口(通过设置edit_item_visible = false)。

I tried v-on-clickaway but since I have a list of items then it would trigger multiple times. 我尝试了v-on-clickaway,但由于我有一个项目列表,因此它将触发多次。 And the @click event would trigger first and then the clickaway event would trigger multiple times and hide it right after showing it. @click事件将首先触发,然后clickaway事件将触发多次,并在显示后立即将其隐藏。 I also tried to change the component's data from outside but with no luck. 我也尝试从外部更改组件的数据,但是没有运气。

Vue.component('item-list', {
    template: `
        <div>
            <div v-for="(item, index) in items" @click="showEdit(index)">
                <div>{{ item.id }}</div>
                <div>{{ item.description }}</div>

                <div v-if="edit_item_visible" class="edit-item">
                    Edit this item here...
                </div>
            </div>
        </div>
    `,

    data()
    {
        return {
            items: [],
            edit_item_visible: false,
            selected: null,
        };
    },

    methods:
    {
        showEdit(index)
        {
            this.selected = index;
            this.edit_item_visible = !this.edit_item_visible;
        }
    },
});

const App = new Vue ({
    el: '#app',
})

If you want to be able to edit multiple items at the same time, you should store the list of edited items, not global edit_item_visible flag. 如果希望能够同时编辑多个项目,则应存储已编辑项目的列表,而不是全局edit_item_visible标志。

    showEdit(item)
    {
        this.selected = item;
        this.editing_items.push(item);
    }


    // v-on-clickaway="cancelEdit(item)"
    cancelEdit(item)
    {
        let idx = this.editing_items.indexOf(item);
        this.editing_items.splice(idx, 1);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM