5

<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
9
  • 1
    May I know the use case of calling a method inside onMounted() ? As per it's name it called when component mounted. For a button click, you can call a method directly. Commented Mar 12, 2022 at 16:41
  • 1
    @CreativeLearner In Vue as far as I observed, Vanillajs code is accessible only within onMounted lifecycle hook and I had some vanilajs code and events with some logic. I needed to call a function, and inside that function I had some events references. Thats why actually I needed to call method defined in onMounted. Commented Mar 12, 2022 at 16:47
  • 1
    But as per the digest cycle this hook will work on component mount and after that if you want to execute any code based on any event that you have to call directly a method. You can access vanilajs code outside of onMounted() method as well. Commented Mar 12, 2022 at 16:49
  • 1
    @CreativeLearner for example let sliders = document.querySelector(".carouselbox"); without put this statement inside onMounted, sliders is not executing when it is inside <script setup lang="ts"> only Commented Mar 12, 2022 at 16:57
  • 1
    It should work, What issue you are facing ? It's just a normal querySelector method. Commented Mar 12, 2022 at 17:02

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

Comments

3

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.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.