vue兄弟通信--窗口随动

效果:左右窗口移动到隐藏后,旁边的小窗口会随着移动贴边。

知识点:兄弟组件通信

1.新建Bus.js文件

Bus.js内容:

import Vue from 'vue';  
export default new Vue(); 
2.引入文件
import Bus from "@/common/js/Bus.js";
(右侧边栏与工具页面都需要加)
3.使用
右侧栏页面:
<div
    class="container"
    :class="openRight ? 'show_bar' : 'hide_bar'"
  >
    <!-- 开关 -->
    <div class="handle" @click="handleClick()">
      <i
        class="iconfont icon_jiantou"
        :class="!openRight ? 'bar_0' : 'bar_180'"
      ></i>
    </div>
//其他代码
</div>
 openRight: false, //右边栏开启开关
 methods: {
    //右侧栏合起开关
    handleClick() {
      this.openRight = !this.openRight;
      //发送给地图工具栏,侧边栏状态
      Bus.$emit("openRight", this.openRight);
    }
 }
.container {
  position: absolute;
  top: 0px;
  width: 388px;
  height: 100%;
  display: inline-block;
  box-sizing: border-box;

  .handle {
    position: absolute;
    top: calc(50% - 76px);
    right: 388px;
    width: 14px;
    height: 76px;
    border-radius: 10px 0px 0px 10px;
    display: inline-block;
    line-height: 76px;
    padding: 0 2px;
    box-sizing: border-box;
    cursor: pointer;
    i {
      font-size: 11px;
      display: inline-block;
    }
  }
  .bar_180 {
    transform: rotate(180deg);
    transition: all 0.5s;
  }
  .bar_0 {
    transform: rotate(0deg);
    transition: all 0.5s;
  }
}
.show_bar {
  right: 0px !important;
  transition: right 0.5s;
}
.hide_bar {
  right: -388px !important;
  transition: right 0.5s;
}

工具栏页面:

<div
    class="toolbar"
    :class="openRight ? 'toolbar_move' : ''"
  >
     工具栏内容
 </div>
openRight: false, //右边栏开启开关
mounted() {
    //接收侧边栏状态
    Bus.$on("openRight", openRight => {
      this.openRight = openRight;
    });
},
.toolbar{
  border-radius: 4px;
  font-size: 20px;
  position: absolute;
  top: 20px;
  right: 20px;
  transition: right 0.5s;
}
.toolbar_move {
  right: 408px;
  transition: right 0.5s;
}

 

核心代码:
(接收!)
 Bus.$on("openRight", openRight => {
      this.openRight = openRight;
    });
(发送!)
 Bus.$emit("openRight", this.openRight);
 
posted @ 2022-11-24 15:03  如意酱  阅读(47)  评论(0编辑  收藏  举报