美文网首页
《Vue.js实战》学习笔记 -下拉菜单

《Vue.js实战》学习笔记 -下拉菜单

作者: 863cda997e42 | 来源:发表于2020-05-06 09:29 被阅读0次

Vue.js实战

可从外部关闭的下拉菜单

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>可从外部关闭的下拉菜单</title>
    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>
    <style>
        [v-cloak] {
            display: none;
        }

        .main {
            width: 125px;
        }

        button {
            display: block;
            width: 100%;
            color: #fff;
            background-color: #39f;
            border: 0;
            padding: 6px;
            text-align: center;
            font-size: 12px;
            border-radius: 4px;
            cursor: pointer;
            outline: none;
            position: relative;
        }

        button:active {
            top: 1px;
            left: 1px;
        }

        .dropdown {
            width: 100%;
            height: 150px;
            margin: 5px 0;
            font-size: 12px;
            background-color: #fff;
            border-radius: 4px;
            box-shadow: 0 1px 6px rgba(0, 0, 0, .2);
        }

        .dropdown p {
            display: inline-block;
            padding: 6px;
        }
    </style>
</head>

<body>
    <div id="app" v-cloak>
        <div class="main" v-clickoutside="handleClose">
            <button @click="show = !show">点击显示下拉菜单</button>
            <div class="dropdown" v-show="show">
                <p>下拉框的内容,点击外面区域可以关闭。</p>
            </div>
        </div>
    </div>
    <script>
        Vue.directive("clickoutside", {
            bind: function (el, binding, vnode) {
                function documentHandler(e) {
                    if (el.contains(e.target)) {
                        return false;
                    }
                    if (binding.expression) {
                        binding.value(e);
                    }
                }
                el.__vueClickOutside__ = documentHandler;
                document.addEventListener('click', documentHandler);
            },
            unbind: function (el, binding) {
                document.removeEventListener('click', el.__vueClickOutside__);
                delete el.__vueClickOutside__;
            }
        });
    </script>
    <script>
        var app = new Vue({
            el: "#app",
            data: {
                show: false
            },
            methods: {
                handleClose: function () {
                    this.show = false;
                }
            },
        });
    </script>

</body>

</html>

相关文章

网友评论

      本文标题:《Vue.js实战》学习笔记 -下拉菜单

      本文链接:https://www.haomeiwen.com/subject/qdlightx.html