Vue.js--下拉菜单组件

效果

在这里插入图片描述#### 入口页面 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <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.js"></script>
    <script src="clickoutside.js"></script>
    <script src="index.js"></script>
</body>
</html>
根实例 index.js
var app = new Vue({
    el: '#app',
    data: {
        show: false
    },
    methods: {
        handleClose () {
            this.show = false;
        }
    }
});
下拉框组件 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);
    },
    unbind: function (el, binding) {
        document.removeEventListener('click', el.__vueClickOutside__);
        delete el.__vueClickOutside__;
    }
});
样式表
[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;
}
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值