【问题标题】:Vue2 call parent method from child in looped componentVue2从循环组件中的子调用父方法
【发布时间】:2018-12-25 04:42:55
【问题描述】:

我正在循环根组件,它有子组件。

<root-select v-for="offer in offers"  >
   <child-options v-for="item in options" >
   </child-options>
</root-select>

但是,当我 $emit 子级的根函数时,我所有的根组件都更改了这些数据。

孩子:

EventBus.$emit('toggle', value);

根:

EventBus.$on('toggle', this.toggle);

但我需要,该数据仅在触发组件中更改。

谢谢。

【问题讨论】:

  • this.toggle 函数有什么作用?
  • 你为什么使用EventBus而不是监听组件上的事件?
  • Karl-André Gagnon,你的意思是这样。$emit('toggle', value) ?
  • 不,我的意思是像&lt;child-options v-for="item in options" @toggle="this.toggle(item)"&gt;,而你的切换功能看起来像(item,value) -&gt; item = value;。当然,我假设toggle 不仅仅只是赋值,否则@toggle="item = $event.value" 就足够了。
  • 有一段时间没接触Vue,所以可能不准确,但逻辑在这里。

标签: javascript vue.js vuejs2 vue-component event-bus


【解决方案1】:

尽量不要使用 Event bus 来发出。使用正常的 Emit 方式从子级发射到父级。

在子组件函数中:

this.$emit('toggle', value);

在父组件函数中:

<template><child-options v-for="item in options" @toggle="onToggleFn"></child-options></template>

<script>
...
methods:{
     onToggleFn:function(){
         //your logic here
     }
}
</script>

【讨论】:

  • 您的回答通俗易懂。谢谢。
猜你喜欢
  • 2017-11-24
  • 2018-07-20
  • 1970-01-01
  • 2020-09-11
  • 2016-12-08
  • 2020-06-15
  • 2020-10-20
  • 2016-12-03
相关资源
最近更新 更多