从Vue中的另一个组件观察某个事件

时间:2018-12-14 12:54:28

标签: javascript vue.js vuejs2

我有两个组成部分:

<div>
    <advertiser-add-component></advertiser-add-component>
    <advertisers-component></advertisers-component>
</div>

这些组件具有以下接口: enter image description here

第一个组件是一个按钮。当我单击它时,将看到一个模式对话框。模态包含一个Ajax形式:

enter image description here

第二个组件是一个表。您已经在第一张照片上看到了 因此,我想在发送表单后不刷新页面的情况下重新呈现表组件。是否有某种方法可以从广告商组件“订阅”此事件(一旦发送了模式信息)?如何用最少的代码组织它?

4 个答案:

答案 0 :(得分:2)

是的,对于这样的事情,您可以启动一个简单的事件总线,您的组件将向总线发出更新,而其他监视总线上该事件类型的更新。

这是一个很好的例子:

https://alligator.io/vuejs/global-event-bus/

答案 1 :(得分:2)

我正在使用vue-events软件包:https://github.com/cklmercer/vue-events

  • 全局安装软件包
  • 在事件组件中添加事件对象以监听事件,并从模式中触发事件,请检查以下示例:

    Component with table Modal sending reload event

答案 2 :(得分:1)

我鼓励您检查以下内容:https://vuejs.org/v2/guide/state-management.html

基本上,您有一个称为存储的组件(或Java类),用于存储表的数据。该数据是表显示的数据。提交模式时,您要求商店再次从我假设已存储数据的后端获取数据(通过发送事件)。

由于该表已经显示了商店的数据,所以该表将自动更新。

我在这里的一个应用程序中https://github.com/Draluy/Jobsearch/blob/master/front/src/components/applications/Application.vue

答案 3 :(得分:0)

似乎您想将两个组件包装在另一个处理数据和ajax请求的组件中。

<wrap-component> <!-- This component contains the data and handles the ajax request -->
   <advertiser-add-component @click-triggered="ajaxRequest"></advertiser-add-component> <!-- This components emits a click event to the <wrap-component>-component that executes the ajax requests -->
   <advertisers-component :tableData="tableData"></advertisers-component> <!-- This component is passed the data via the tableData prop -->
</wrap-component>

<!-- Inside "wrap-component" -->
data() {
  return {
    tableData: []
  }
},
methods: {
  ajaxRequest() {
   // make the data request here and replace this.tableData with the response data
  }
}

<!-- Inside "advertiser-add-component" -->
methods: {
  // Execute this function, when the button is clicked
  add() {
    this.$emit('click-triggered');
  }
}

<!-- Inside "advertisers-component" -->
props: {
   tableData: {
      type: Array // if the data is an array of course..
   }
}