<!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>vue指令 下拉菜单显示隐藏</title>
<link rel="stylesheet" href="">
<script src="./vue.js"></script>
<style>
.click-parent{
margin:200px auto;
position: relative;
width: 200px;
height: 200px;
color: #000;
}
.click-div{
width: 100%;
height: 30px;
line-height: 30px;
background: aliceblue;
}
.drop-div{
box-sizing: border-box;
position: absolute;
left: 0;
top: 30px;
border: 1px solid #aaa;
padding: 8px;
width: 100%;
}
</style>
</head>
<body>
<div id="app">
<div v-clickoutside="close" class="click-parent">
<div class="click-div" @click="show=!show">点击打开下拉菜单</div>
<div class="drop-div" v-show="show">我是下拉内容</div>
</div>
</div>
<script>
Vue.directive('clickoutside', {
bind: function (el, binding) {
function documentHandler(e) {
// el内部的不需要处理
if (el.contains(e.target) && e.keyCode !== 27) {
return false
}
if (binding.expression) {
binding.value(e)
}
}
function keyUp(e) {
if (e.keyCode === 27) {
if (binding.expression) {
binding.value(e)
}
}
}
// 将事件作为el的变量,方便解绑时调用
el.vueClickOutside = documentHandler
el.vueKeyUp= keyUp
document.addEventListener('click', documentHandler)
document.addEventListener('keyup', keyUp)
},
unbind: function (el, binding) {
document.removeEventListener('click', el.vueClickOutside)
delete el.vueClickOutside
document.removeEventListener('keyup', el.vueKeyUp)
delete el.vueKeyUp
}
})
new Vue({
el:'#app',
data:{
show: false
},
methods: {
close() {
this.show = false
}
}
})
</script>
</body>
</html>
报错: [Vue warn]: Failed to resolve directive: clickoutside (found in <Anonymous>)
原因: 指令名称包含大写
解决:改为小写