在 Vue 3 项目中,我有以下设置。有一个单独的 stuff.ts
文件,其中包含一些辅助函数,我想在我的模板中使用它。
<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>
据我所知,该函数已正确导入,并在我将其登录到 onMounted()
时定义。
但是当我单击链接并尝试从模板中执行 doSomething()
时,它说函数未定义。我是 Vue 3 的新手,但我想我必须做一些事情来准备该功能并使其可用。
如何使导入的函数可用于我的模板?我是否必须改为调用组件方法并在其中使用 doSomething
?
最佳答案
最简单的方法是通过设置函数的返回来“转发”它
<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>
关于javascript - 如何在 Vue 3 模板中使用导入函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68008445/