[英]Best way to a vue instance (app1) call another vue instance (app2)
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 ?如何在 APP2 中对 Vue 说我需要调用 APP1 ?
I need that both buttons "run APP1" do exactly the same thing.我需要两个按钮“运行 APP1”做同样的事情。 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.
假设在插图中,第一个正在工作,第二个是复制/粘贴......但第二个不起作用,因为它进入了 app2。
Concrete case: see "GOOD1" and "GOOD2" buttons at this code similar to the used in the last question ...具体案例:请参阅此代码中的“GOOD1”和“GOOD2”按钮,类似于上一个问题中使用的...
Every Vue instance implements an events interface .每个 Vue 实例都实现了一个事件接口。 This means that to communicate between two Vue instances (
app1
and app2
) you can use Custom Events .这意味着要在两个 Vue 实例(
app1
和app2
)之间进行通信,您可以使用自定义事件。
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):并从中发出事件(此代码位于
app1
的模板中):
<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
:在第二个实例(
app2
)中,使用$on
监听这些事件:
new Vue({
el: '#app2',
// ...
mounted() {
app1.$on('go-modal', this.handleApp1);
},
methods: {
handleApp1(data) {
this.header = data.header;
this.showModal = data.showModal;
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.