我需要从Vue应用程序外部调用组件中的方法。我在main.ts文件中定义了发送方法。我不确定如何获取对App组件的引用,以便在其中传递消息。
import Vue from 'vue';
import App from './App.vue';
Vue.config.productionTip = false;
let win = window as any;
win.player = new Vue({
render: (h) => h(App),
methods: {
send(data: string) {
// I need to get App reference here
}
}
}).$mount('#app');
答案 0 :(得分:0)
您可以将Vue
实例绑定到const
上,并通过访问实例中的方法(就像它是“常规”对象一样)从实例外部调用它:
// INSIDE OF OUR VUE INSTANCE
const vm = new Vue({
el: "#app",
methods: {
alertClickHandler(message) {
alert(message)
}
}
})
// OUTSIDE OF OUR VUE INSTANCE
function outsideVueClick(message) {
vm.alertClickHandler(message);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<p>Click each button</p>
<!-- OUTSIDE OF OUR VUE INSTANCE -->
<button onclick="outsideVueClick('OUTSIDE VUE')">I am OUTSIDE of Vue</button>
<!-- INSIDE OF OUR VUE INSTANCE -->
<div id="app">
<br/>
<button @click="alertClickHandler('INSIDE VUE')">I am INSIDE of Vue</button>
</div>