【问题标题】:adding component to parent from child in vue在 vue 中从子级向父级添加组件
【发布时间】:2020-02-23 03:27:11
【问题描述】:

我的根组件的结构是这样的:

<Header />
<router-view />
<Footer />

在某些页面上,我想通过将带有按钮的组件从路由器视图的子组件传递到标题组件来向标题添加一些额外的按钮。由于我们在谈论按钮,所以我需要能够监听点击事件并处理子组件中的事件。

我知道如何将信息从父组件传递给子组件,并且我知道如何从子组件发出事件以由父组件处理,但这似乎不是正确的方法(我可能错了)。

我可能遗漏了一些东西,但我不知道如何将组件从 CHILD 传递给 PARENT。

有什么想法吗?

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    与其尝试像这样在组件之间直接传递数据,不如看看创建一个event bus。在这种情况下,它只是另一个 Vue 实例,但您可以像普通的 Vue 实例一样订阅和发出事件,允许 2 路数据通信。

    来自文章:

    // ./event-bus.js
    import Vue from 'vue';
    export const EventBus = new Vue();
    

    在总线上发送事件:

    // PleaseClickMe.vue
    <template>
      <div class="pleeease-click-me" @click="emitGlobalClickEvent()"></div>
    </template>
    
    <script>
    // Import the EventBus we just created.
    import { EventBus } from './event-bus.js';
    
    export default {
      data() {
        return {
          clickCount: 0
        }
      },
    
      methods: {
        emitGlobalClickEvent() {
          this.clickCount++;
          // Send the event on a channel (i-got-clicked) with a payload (the click count.)
          EventBus.$emit('i-got-clicked', this.clickCount);
        }
      }
    }
    </script>
    

    收听公交车上的活动:

    // Import the EventBus.
    import { EventBus } from './event-bus.js';
    
    // Listen for the i-got-clicked event and its payload.
    EventBus.$on('i-got-clicked', clickCount => {
      console.log(`Oh, that's nice. It's gotten ${clickCount} clicks! :)`)
    });
    

    现在您只需检查 URL 并根据显示的路线更改按钮。

    【讨论】:

    猜你喜欢
    • 2021-04-16
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 2014-09-15
    相关资源
    最近更新 更多