Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to a vue instance (app1) call another vue instance (app2)

Tags:

vue.js

vuejs2

Example:

    <div id="app1">  <button @click="etc...">run APP1</button> ..</div>

    <div id="app2">...   
      <button @click...>run APP1</button><!-- HERE! need a reference--> ...
      <button @click...>run APP2</button> 
    </div>

How to say to Vue in APP2 that I need to call APP1?

I need that both buttons "run APP1" do exactly the same thing. Supposing that, in the illustration, the first is working, and the second is a copy/paste... But the second will not work because is into app2.

Concrete case: see "GOOD1" and "GOOD2" buttons at this code similar to the used in the last question...

like image 229
Peter Krauss Avatar asked Nov 15 '25 09:11

Peter Krauss


1 Answers

Every Vue instance implements an events interface. This means that to communicate between two Vue instances (app1 and app2) you can use Custom Events.

So, in your example, before anything, give the first instance (that will emit events) a name so the other instance can reference it:

var app1 = new Vue({
  el: '#app1'
})

And emit events from it (this code is at app1's template):

  <button @click="$emit('go-modal', {header: 'HEL<big>LO2</big>', showModal: true})">GOOD1</button>
  
  <button @click="$emit('go-modal', {header: 'BYE2', showModal: true})">GOOD2</button>

In the second instance (app2), listen to those events using $on:

new Vue({
  el: '#app2',
  // ...
  mounted() {
    app1.$on('go-modal', this.handleApp1);
  },
  methods: {
    handleApp1(data) {
      this.header = data.header;
      this.showModal = data.showModal;
    }
  }
})

See demo JSFiddle here.

like image 122
acdcjunior Avatar answered Nov 17 '25 05:11

acdcjunior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!