Trigger Method in Sibling Component Vue JS

血红的双手。 提交于 2021-02-05 08:23:06

问题


need your assistance once again. Here's my situation. VueJS2 (vue-cli project) no Vuex. I have parent component, child1 and child2. child1 is a form that gets data from child2(which is a table). Upon clicking on table row's checkbox in child2, we fill up the form in child1 this is done by event emitting via parent(picture 2). child1 has a button and reset method(see picture 1) to clear its fields. My task is: when I 'uncheck' checkbox in table row child2, form in child1 has to be cleared. How do I do this, specifically, how do I access reset method in child1 from child2 and use that method from child2 basically. I know how to pass data from child to child, but cant get my head around how to be able just manipulate child's data from its sibling. Please help! Thank you in advance!


回答1:


If I understand it correctly, you have 2 child components, and you want to tell child1 to execute a method (reset) from your child2 compoent without passing any props.

Well, in that cases your option is limited to using an event Bus.

Check this example. When you click on a button from CompB it executes a methods inside another child component: CompA

var Bus = new Vue()

var compA = {
  data: () => ({ name: 'Primary' }), 
  
  template: `<p> Comp A is: {{name}}</p>`,
  
  methods: {
    reset () {
      this.name = 'RESETED'
    }
  },
  
  created () {
   let self = this;
    Bus.$on('resetA', function (payload) {
      self.reset()
    })
  }
}

var compB = {
  template: `<p> Comp B <button @click="resetCompA"> Clear A </button> </p>`,
  methods: {
    resetCompA () {
      Bus.$emit('resetA')
    }
  }
}

new Vue({
  el: '#app',
  components: {
   'comp-a'  : compA, 
   'comp-b' : compB
  }
})
<script src="https://unpkg.com/vue@2.5.9/dist/vue.js"></script>
<div id="app">
  <comp-a></comp-a>
  <comp-b></comp-b>
</div>


来源:https://stackoverflow.com/questions/49564379/trigger-method-in-sibling-component-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!