Donny Gunawan
Donny Gunawan

Reputation: 363

Vue call sibling's method

<root>
   <my-button @click="save()"/>
   <my-form/>
</root>

my-form.vue

methods:{
   save(){}
}

How to call save() from my-form via my-button?

Upvotes: 0

Views: 1182

Answers (1)

Tomer
Tomer

Reputation: 17930

You can use an event bus:

let EventBus = new Vue();

let MyButton= Vue.extend({
    name: "my-button",
  props: ["what"],
  template: `
    <button class="btn btn-md btn-success the-button" @click="save()">Sender: {{what}}</button>
  `,
  methods: {
    save: function(){
        EventBus.$emit("form.save", //pass payload here);
    }
  }
});

Vue.component("my-button", MyButton);

***my-form.vue:****

 created(){
     EventBus.$on('form.save', (payload)=>{
         this.save(payload)
    });
},
methods:{
    save(payload) {}
}

Full working sample: https://jsfiddle.net/arvidkahl/gxdn6ycv/17/

Upvotes: 2

Related Questions