vue3跨组件通信:一个页面的按钮可以控制另一个页面的div显隐

可以使用Vuex进行状态管理

1.安装vuex

npm install vuex@next

2.创建一个store.js文件

// store.js
import { createStore } from 'vuex';
 
export default createStore({
  state: {
    PanelVisible: false
  },
  mutations: {
    showPanel(state) {
      state.PanelVisible = !state.PanelVisible;
    }
  }
});

3.在main.js里使用store

import store from './store';

app.use(store)

4.在组件页面中,绑定一个按钮来改变状态:

<template>
  <div class="headerContainer">
    <span class="headerTitle">编辑空间</span>
    <div class="editBox" @click="showPanel">
      <img src="../../assets/img/edit.png" alt="" />
    </div>
  </div>
</template>
<script setup>
import { useStore } from 'vuex'
import { ref, reactive, onMounted } from 'vue'
const store = useStore()
const showPanel = () => {
  store.commit('showPanel')
}
onMounted(() => {})
</script>

<style scoped lang="scss">
.headerContainer {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
}
.headerTitle {
  font-size: 24px;
  line-height: 24px;
}
.editBox {
  width: 20px;
  height: 20px;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>

5.在另一个页面中,控制div的显隐

<template>
  <div class="about">
    <el-container>
      <el-header><Header></Header></el-header>
      <el-main>
        <div class="panel" v-show="isPanelVisible">
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed, inject } from 'vue'
import Header from '../components/HeadArea/Header.vue'
const store = inject('store')
const isPanelVisible = computed(() => store.state.PanelVisible)
onMounted(() => {})
</script>

<style scoped lang="scss">
.about {
  width: 100%;
  height: 100vh;
}
:deep(.el-header) {
  --el-header-padding: 0 !important;
  background-color: #edf9ff;
  height: 4vh;
}
:deep(.el-main) {
  --el-main-padding: 0 !important;
  background-color: #fef8f8 !important;
  height: 96vh !important;
}
.panel {
  position: absolute;
  right: 0;
  width: 400px;
  height: 96vh;
  background-color: #e7f0ff;
}
</style>

最终效果:点击按钮能控制面板的显隐

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值