v-close放在点击不关闭下拉框的标签上
<!-- 搜索 -->
<div class="search-bar-package search_bar-package" v-close>
<div class="div_form">
<div class="opt">
专业
<img src="../assets/images/sanjiao.png" alt @click="showopt" />
</div>
<input
class="div_form_search"
type="search"
autocomplete="off"
placeholder="搜索专业"
/>
<button class="submit-button fit-button">搜索</button>
<div class="searchOpt" v-if="showOpt">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
</div>
</div>
与data同级
directives: {
close: {
inserted(el, binding, vnode) {
window.addEventListener("click", (e) => {
if (!el.contains(e.target)) {
vnode.context.showOpt = false;
}
});
},
},
},
另一种方式:
是在聚焦textarea框的时候,高度变大,点击其他地方高度恢复(用了上边的不生效,也不知道为啥),用这种方法也是把这部分抽离出来当成一个组件用才生效(还没整明白问题 出在哪里)
<template>
<div>
<div class="reply-input" v-clickoutside="handle">
<textarea
type="text"
placeholder="回复评论"
v-model="content"
@focus="textareafocus"
:style="!heightchange || 'height:68px'"
/>
<el-popover placement="bottom" width="300" trigger="click">
<emotion
@emotion="handleEmotion"
class="emotion"
:height="200"
></emotion>
<img
slot="reference"
class="imgs"
src="../assets/images/fire.png"
alt=""
/>
</el-popover>
</div>
</div>
</template>
<script>
import Emotion from "../components/Emotion/index.vue";
const clickoutside = {
// 初始化指令
bind(el, binding, vnode) {
function documentHandler(e) {
// 这里判断点击的元素是否是本身,是本身,则返回
if (el.contains(e.target)) {
return false;
}
// 判断指令中是否绑定了函数
if (binding.expression) {
// 如果绑定了函数 则调用那个函数,此处binding.value就是handleClose方法
binding.value(e);
}
}
// 给当前元素绑定个私有变量,方便在unbind中可以解除事件监听
el.__vueClickOutside__ = documentHandler;
document.addEventListener("click", documentHandler);
console.log(111);
},
unbind(el, binding) {
console.log(1211);
// 解除事件监听
document.removeEventListener("click", el.__vueClickOutside__);
delete el.__vueClickOutside__;
},
};
export default {
name: "Reply",
components: {
Emotion,
},
data() {
return {
heightchange: false,
};
},
directives: { clickoutside },
methods: {
handle() {
console.log(111333);
if (!this.content) {
this.heightchange = false;
}
console.log(this.heightchange);
},
handleEmotion(i) {
this.content += i;
},
textareafocus() {
console.log(23);
this.heightchange = true;
},
},
};
</script>