简体   繁体   中英

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).

I tried v-on-clickaway but since I have a list of items then it would trigger multiple times. And the @click event would trigger first and then the clickaway event would trigger multiple times and hide it right after showing it. 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.

    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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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