在Vue中将组件从子组件添加到父组件 [英] adding component to parent from child in vue

查看:79
本文介绍了在Vue中将组件从子组件添加到父组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的根组件的结构类似于:

The structure of my root component is something like:

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

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

On some pages I would like to add some additional buttons to the header by passing a component with buttons from the child component of the router-view to the Header-component. Since we are talking about buttons, I need to be able to listen for the click events and handle the events in the child component.

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

I know how to pass information from parent to child and I know how to emit events from child components to be handled by parent components, but this doesn't seem like the right way (I might be wrong).

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

I might be missing something, but I cannot figure out how to pass components from CHILD to PARENT.

有什么想法吗?

推荐答案

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

Instead of trying to pass data directly between components like this, you should take a look at creating an event bus. In this case, it's just another Vue instance, but you can subscribe to and emit events on it just like a regular Vue instance, allowing 2 way data communication.

来自文章:

// ./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 并根据显示的路由更改按钮.

Now you can just check the URL and change the buttons depending on what route is displayed.

这篇关于在Vue中将组件从子组件添加到父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆