父组件,index界面,注意此时expend按钮在父组件中
<template>
<el-container>
<el-aside class="Aside">
<MAside @expendClick="expendClick" :message="message" />
</el-aside>
<div class="expend" @click="expend">
<el-icon class="move" style="margin: 0"><DArrowLeft /></el-icon>
</div>
<el-container>
<el-main style="--el-main-padding: 0">
<router-view />
</el-main>
</el-container>
</el-container>
</template>
<script>
import MAside from "../components/MAside.vue";
export default {
name: "Admin",
components: {
MAside,
},
data() {
return {
isCollapse: true,
message: false,
};
},
created() {
//创建页面之后一段时间自动收缩
setTimeout(() => {
this.expend();
}, 1000);
},
methods: {
//展开收缩
expend() {
if (this.isCollapse) {
this.isCollapse = false;
this.message = false;
document.querySelector(".Aside").style.width = 0;
document.querySelector(".Aside").style.opacity = 0;
document.querySelector(".expend").style.left = "-25px";
document.querySelector(".expend").style.transform =
"rotate(180deg) translateY(10%)";
} else {
this.isCollapse = true;
this.message = true;
this.message = this.isCollapse;
document.querySelector(".Aside").style.width = "25%";
document.querySelector(".Aside").style.opacity = 1;
document.querySelector(".expend").style.left = "25%";
document.querySelector(".expend").style.transform =
"rotate(0deg) translateY(-10%)";
}
},
//当展开时点击子组件以外地方子组件可调用此父组件的函数,
expendClick() {
if (this.isCollapse) {
this.expend();
}
},
},
};
</script>
子组件,侧边导航栏,用父子间的传参 配合watch来监听侧边栏是否展开,展开则添加点击监听函数,收缩则去除点击监听函数。判断点击是否点击到aside组件外可以通过检查目标元素(e.target)是否不包含在组件的根元素(this.$el)中,如果目标元素在组件之外,我们调用父组件的函数expendClick()来实现自动收缩,另外因为expend按钮在父组件中,点击按钮也会被判定为false,导致按钮展开功能失效
<template>
<div class="aside">
<el-scrollbar style="height: 100%">
<ul class="item_ul">
<li
@click="change"
class="item_li"
data-index="0"
data-routeName="mobileTackOff"
:class="active == 'mobileTackOff' ? 'active' : ''"
>
<el-icon style="margin: 0">
<Calendar />
</el-icon>
</li>
<li
@click="change"
class="item_li"
data-index="1"
data-routeName=""
:class="active == 1 ? 'active' : ''"
>
<el-icon style="margin: 0">
<Stamp />
</el-icon>
</li>
</ul>
</el-scrollbar>
</div>
</template>
<script>
export default {
name: "MAside",
props: ["message"],
data() {
return {
active: "",
};
},
created() {
this.active = this.$route.name;
},
watch: {
message(value) {
console.log(value);
//注意需要先让父组件的expend函数先执行完之后在执行toggleClickEventListener()来添加监听事件
setTimeout(() => {
this.toggleClickEventListener(value);
}, 100);
},
},
methods: {
change(e) {
this.active = e.target.dataset.routeName;
this.$router.push({ name: e.target.dataset.routeName });
},
handleOutsideClick(e) {
if (!this.$el.contains(e.target)) {
this.$emit("expendClick");
}
},
toggleClickEventListener(value) {
//判断如果展开了,则添加监听事件
if (value) {
document.addEventListener("click", this.handleOutsideClick);
//未展开 则删除监听事件,否则影响父组件收缩展开按钮的正常功能
} else {
document.removeEventListener("click", this.handleOutsideClick);
}
},
},
};
</script>
实现效果如下
此时是展开侧边栏,添加了点击监听事件,这时我们点击侧边栏以外部分
点击这部分
侧边栏就自动收缩啦