首页 > 解决方案 > 如何向 vue.js 中不是父级的另一个组件发出事件?

问题描述

因此,下面示例中的第一个组件只是简单地导入其他组件,然后在模板中呈现它们。在要导入的组件中,我有一个 Stages 组件和一个 StageExecutionTimes 组件。我想要做的是当用户单击 Stage 组件中的图标时,我想隐藏 StageExecutionTimes 组件。我的理解是,我需要使用$emitStages 组件将事件发送到父级,然后父级将隐藏 StageExecutionsComponent。我正在尝试设置showgraph为布尔值,然后将其用作组件之间的道具。然后我试图改变showgraphvia的值$emit

下面的代码似乎不会影响或改变showgraph主组件中的值

导入和渲染子组件的主组件

<template>
  <div id="vue-main">
    <NavBar></NavBar>
    <transition name="fade">
      <div :v-bind="showgraph"><StageExecutionTimes></StageExecutionTimes></div>
    </transition>
    <transition name="fade">
      <Stages></Stages>
    </transition>
    <transition name="fade">
      <Overview></Overview>
    </transition>
    <Footer></Footer>
  </div>
</template>

<script>
import NavBar from "../components/NavBar.vue";
import Stages from "../components/execution_details/Stages.vue";
import Binaries from "../components/execution_details/Binaries.vue";
import StageExecutionTimes from "../components/graphs/StageExecutionTimes.vue";
import Overview from "../components/execution_details/Overview.vue";

export default {
  name: "execution_details",
  data() {
    return {
      loading: true,
      showgraph: true
    };
  },
  components: {
    NavBar,
    Stages,
    StageExecutionTimes,
    Overview,
  },

../components/execution_details/Stages.vue";

  <template>
  <div class="stages">
    <template v-if="job_execs.length > 0">
    <h3>Stages</h3>
    <a href="#" @click="!showgraph"><img src="@/assets/charticon.png"></a>
    <transition name="fade" appear mode="out-in">
    <table>
      <tbody>
        <template v-for="item in job_execs">
          <tr>
            <td
              v-for="stage_execution in item.stage_execution"
              :class="stage_execution.status.name"
              :title="stage_execution.exec_node.name"
              :key="stage_execution.stage.name"
            >
              <br />
              {{ stage_execution.duration | durationReadable }}
              <br />
              {{ stage_execution.status.name }}
            </td>
          </tr>
        </template>
      </tbody>
    </table>
  </transition>
  </template>
  </div>
</template>

<script>
import { calculateDuration } from "../../helpers/time.js";
import { liveDuration } from "../../helpers/time.js";
import moment from "moment";

export default {
  name: "Stages",
  props: ["showgraph"],
  data() {
    return {
      job_execs: []
    };
  },

在 Stages 组件中单击 charticon 时,如何隐藏 StageExecutionTimes 组件?

另外,我可以在不触及 StageExecutionTimes 组件的情况下完成此操作吗?似乎我可以将事件从 Stages 传递到主要组件,然后从那里隐藏 StageExecutionTimes。

标签: vue.js

解决方案


如果您有许多组件要共享数据,则需要一个 vuex 存储。您单击然后更改商店中的数据,然后在您使用 v-if="isShow"

@click="hideOtherComponent"

hideOtherComponent(){
     this.store.commit('HIDE_COMPONENT');
}

computed: {
    isShow() {
    return store.state.StageExecutionTimesShow
    }
}

<component v-if="isSHow">

` vuex


推荐阅读