Home > Back-end >  How to call a function defined in "onMounted" lifecycle hook in Vuejs?
How to call a function defined in "onMounted" lifecycle hook in Vuejs?

Time:03-13

<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

CodePudding user response:

As per it's name onMounted(), This life cycle hook always execute when component mounted for the first time. For a button click, you can call a method directly outside of this onMounted().

<button @click="callSomething">Click</button>

function callSomething() {
   // Logic can come directly here.
}

CodePudding user response:

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