简体   繁体   中英

How to call Vue 3 method from outside the app

what I want is to call a method, declared in vue 3 app form outside the component of the page. So what I did sofar:

App.vue

<script setup>
 
function test(){
console.log('test');
}
</script>

vue.js

import { createApp } from 'vue'
import App from 'App.vue'

window.app = createApp(App).mount('#app')

index.html

<div id="app"></app>
<script src="app.js"></script>

<script>
 fuction callTest(){
   window.app.test() // <-- this returns undefined
 }
</script>

however it worked with vue2. Any idea how to get it work with vue3?

You need to use defineExpose inside in the first file in order to use it outside the component:

<script setup>
 
function test(){
 console.log('test');
}
defineExpose({
 test
})
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM