Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a function defined in "onMounted" lifecycle hook in Vuejs?

<script setup lang="ts">

function callSomething() {
   something(); //not working
}

onMounted(() => {
function something() {
    console.log("Hello, World");
 }
});
</script>
<template>
    <div>
        <button @click="callSomething">Click</button>
    </div>
</template>

In Vuejs I want to call a function from <script setup lang="ts"> which is defined in onMounted lifecycle hook. Though, I can call function/method from onMounted that defined in <script setup lang="ts">

Error in console:

Uncaught TypeError: something is not a function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The something function is defined only in the scope of the onMounted callback, try to define it outside it to be available for the hook and the other function :


<script setup lang="ts">

function callSomething() {
   something(); //not working
}

function something() {
    console.log("Hello, World");
 }
onMounted(() => {

});
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading