Vue: 下拉菜单

index.html:


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>示例</title>
    <link rel="stylesheet" type="text/css" href="style.css">

</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 src="https://unpkg.com/vue/dist/vue.min.js"></script>
    <script src="clickoutside.js"></script>
    <script src="index.js"></script>
</body>
</html>

clickoutside.js:

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);
    },
    undind: function (el, binding) {
        document.removeEventListener('click', el__vueClickOutside__);
        delete el.__vueClickOutside__;
    }
})

index.js:

var app = new Vue({
    el: '#app',
    data: {
        show: false
    },
    methods: {
        handleClose: function () {
            this.show = false;
        }
    }
});

style.css:

[v-clock] {
    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;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1 Webpack 1.1 概念简介 1.1.1 WebPack是什么 1、一个打包工具 2、一个模块加载工具 3...
    Kevin_Junbaozi阅读 6,714评论 0 16
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,632评论 1 45
  • 北京2018年4月1日上午,NBA常规赛勇士客战国王的比赛中,发生了令人痛心不已的一幕。比赛进行到第三节还有41...
    Curry_宇阅读 1,238评论 1 1
  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,796评论 1 92
  • 酸模叶蓼(学名:Polygonum lapathifolium L.)是蓼科,蓼属一年生草本植物。高可达90厘米。...
    无奈永恒阅读 1,049评论 1 3