【问题标题】:Hide popup box when clicked anywhere on the document单击文档上的任意位置时隐藏弹出框
【发布时间】:2019-01-29 08:51:45
【问题描述】:

我正在尝试制作一个包含项目列表的组件,当我单击每个项目时,它会显示一个编辑弹出窗口。当我再次单击它时,它会隐藏编辑弹出窗口。但我还希望能够单击文档上的任意位置并隐藏所有编辑弹出窗口(通过设置 edit_item_visible = false)。

我尝试了 v-on-clickaway,但因为我有一个项目列表,所以它会触发多次。 @click 事件将首先触发,然后 clickaway 事件将多次触发并在显示后立即隐藏。我也尝试从外部更改组件的数据,但没有成功。

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',
})

【问题讨论】:

标签: javascript vue.js


【解决方案1】:

如果您希望能够同时编辑多个项目,您应该存储已编辑项目的列表,而不是全局 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);
    }

【讨论】:

  • 我的 cancelEdit 函数在 showEdit 函数之后触发,所以它显示它然后立即隐藏它。
  • hmmm...你能在cancelEdit中检查事件目标吗?
  • v-on-clickaway="cancelEdit($event)" - 给我错误 $event is not defined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-19
  • 1970-01-01
  • 2013-07-24
  • 2015-12-29
  • 2018-04-06
  • 2013-06-08
  • 1970-01-01
相关资源
最近更新 更多