In a Vue 3 project, I have the following setup. There is a separate stuff.ts file with some helper functions in it and I want to use it in my template.
<script lang="ts">
import { defineComponent, onMounted } from 'vue'
import { doSomething } from '@/helpers/stuff.ts'
export default defineComponent({
setup(){
onMounted(() => console.log(doSomething)) //<-- logs here okay
}
})
</script>
<template>
<!-- ERROR: doSomething is not a function -->
<a href="#do" @click="doSomething()">Do Something</a>
</template>
As far as I can tell, the function is properly imported and it’s defined when I log it in onMounted().
But when I click the link and try to doSomething() from the template, it says the function isn’t defined. I’m new to Vue 3, but I imagine I have to do something to prep the function and make it available.
How can I make an imported function available to my template? Do I have to call a component method instead and use doSomething inside that?
Advertisement
Answer
The simplest way is to just “forward” it via the return of your setup function
<script lang="ts">
import { defineComponent, onMounted } from 'vue'
import { doSomething } from '@/helpers/stuff.ts'
export default defineComponent({
setup(){
onMounted(() => console.log(doSomething)) //<-- logs here okay
return { doSomething }
}
})
</script>
<template>
<!-- ERROR: doSomething is not a function -->
<a href="#do" @click="doSomething()">Do Something</a>
</template>