Home > Net >  How to call Vue 3 method from outside the app
How to call Vue 3 method from outside the app

Time:07-13

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?

CodePudding user response:

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