显隐
通过模块方式定义指令
-
directive>hidden>index.js
:::details 点击查看代码
import hidden from "./hidden";
const install = function(Vue) {
Vue.directive("hidden", hidden);
};
if (window.Vue) {
window["hidden"] = hidden;
Vue.use(install);
}
hidden.install = install;
export default hidden;
::: -
directive>hidden>hidden.js
:::details 点击查看代码
export default {
bind(el, binding) {
function documentHandler(e) {
if (el.contains(e.target)) {
return false;
}
if (binding.expression) {
binding.value(flag);
}
}
el.menuFun = documentHandler;
document.addEventListener("click", el.menuFun,true);
},
unbind(el) {
document.removeEventListener("click", el.menuFun,true);
delete el.menuFun;
},
};:::
-
home.vue
:::details 点击查看代码
<template>
<div
class="box"
style="width:200px;height:200px;background-color:red"
v-hidden="
(flag) => {
show = flag;
}
"
>
<button @click="show = !show">切换</button>
<div
class="content"
style="width:100px;height:100px;background-color:yellow"
v-show="show"
></div>
</div>
</template>
<script>
import hidden from 'directives/hidene'
export default{
directives:{
hidden
}
}
</script>:::
通过组件方式定义指令
-
home.vue
:::details 点击查看代码
<template>
<div
class="box"
style="width:200px;height:200px;background-color:red"
v-hidden="
(flag) => {
show = flag;
}
"
>
<button @click="show = !show">切换</button>
<div
class="content"
style="width:100px;height:100px;background-color:yellow"
v-show="show"
></div>
</div>
</template>
<script>
export default{
directives: {
hidden: {
bind(el, binding) {
function documentHandler(e) {
if (el.contains(e.target)) {
return false;
}
if (binding.expression) {
binding.value(flag);
}
}
el.menuFun = documentHandler;
document.addEventListener("click", el.menuFun,true);
},
unbind(el) {
document.removeEventListener("click", el.menuFun,true);
delete el.menuFun;
},
},
},
}
</script>:::