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.
JavaScript
x
16
16
1
<script lang="ts">
2
import { defineComponent, onMounted } from 'vue'
3
import { doSomething } from '@/helpers/stuff.ts'
4
5
export default defineComponent({
6
setup(){
7
onMounted(() => console.log(doSomething)) //<-- logs here okay
8
}
9
})
10
</script>
11
12
<template>
13
<!-- ERROR: doSomething is not a function -->
14
<a href="#do" @click="doSomething()">Do Something</a>
15
</template>
16
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
JavaScript
1
17
17
1
<script lang="ts">
2
import { defineComponent, onMounted } from 'vue'
3
import { doSomething } from '@/helpers/stuff.ts'
4
5
export default defineComponent({
6
setup(){
7
onMounted(() => console.log(doSomething)) //<-- logs here okay
8
return { doSomething }
9
}
10
})
11
</script>
12
13
<template>
14
<!-- ERROR: doSomething is not a function -->
15
<a href="#do" @click="doSomething()">Do Something</a>
16
</template>
17