gpt4 book ai didi

vue.js - vue 实例 (app1) 调用另一个 vue 实例 (app2) 的最佳方式

转载 作者:搜寻专家 更新时间:2023-10-30 22:43:19 28 4
gpt4 key购买 nike

例子:

    <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>

如何在 APP2 中对 Vue 说我需要调用 APP1

我需要两个按钮“运行 APP1”做完全相同的事情。假设,在插图中,第一个正在运行,第二个是复制/粘贴...但是第二个将无法运行,因为它在 app2 中。

具体案例:参见“GOOD1”和“GOOD2”按钮at this code类似于 last question 中使用的...

最佳答案

每个 Vue 实例都实现了一个 events interface .这意味着要在两个 Vue 实例(app1app2)之间进行通信,您可以使用 Custom Events .

所以,在你的例子中,在任何事情之前,给第一个实例(将发出事件)一个名字,以便另一个实例可以引用它:

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

并从中发出事件(此代码位于 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>

在第二个实例 (app2) 中,使用 $on 监听这些事件:

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

参见 demo JSFiddle here .

关于vue.js - vue 实例 (app1) 调用另一个 vue 实例 (app2) 的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49203490/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com