如何在 Vuejs 中调用 "onMounted" 生命周期钩子中定义的函数?

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>

Vuejs 中,我想从 <script setup lang="ts"> 调用一个在 onMounted 生命周期挂钩中定义的函数。不过,我可以从 <script setup lang="ts">

中定义的 onMounted 调用 function/method

控制台错误:

Uncaught TypeError: something is not a function

something 函数仅在 onMounted 回调的范围内定义,请尝试在其外部定义它以供 hook 和其他函数使用:


<script setup lang="ts">

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

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

});
</script>

根据它的名字onMounted(),这个生命周期钩子总是在第一次安装组件时执行。对于单击按钮,您可以直接在此 onMounted().

外部调用方法
<button @click="callSomething">Click</button>

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