user1908375
user1908375

Reputation: 1089

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?

Upvotes: 1

Views: 1332

Answers (1)

Ibrahim Zanbily
Ibrahim Zanbily

Reputation: 61

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>

Upvotes: 3

Related Questions