Vue3中辅助函数与组合式函数均报‘is not a function’错误求助
问题解决:Uncaught TypeError: helperFunction is not a function
错误根源及修复步骤:
辅助函数导出方式错误
你的辅助函数文件里用了export default { helperFunction },这会导出一个包含helperFunction属性的对象,但组件里是直接默认导入成函数,导致实际拿到的是个对象而非函数本身。
修复辅助函数的导出:const helperFunction = (element, text, index) => { if (index === 0) { element.innerHTML = '' } element.innerHTML += text[index] if (index === text.length - 1) { return } setTimeout(() => helperFunction(element, text, index + 1), 100) } // 直接导出函数,而非包裹在对象里 export default helperFunction组件调用时未获取ref的实际DOM元素
组件里的paragraphRef是Vue的ref响应式对象,直接传给辅助函数拿不到DOM节点,需要用.value获取实际元素:
修复组件里的点击事件:const paragraphClick = () => { // 确保ref已绑定到DOM元素再调用 if (paragraphRef.value) { helperFunction(paragraphRef.value, props.paragraphText, 0) } }辅助函数递归调用参数缺失
原辅助函数里的setTimeout(() => helperFunction(index + 1), 100)只传了index,漏掉了element和text参数,会导致后续递归调用参数错误,需要补全:setTimeout(() => helperFunction(element, text, index + 1), 100)
完整修复后的代码:
组件代码:
<template> <p ref="paragraphRef">i am a paragraph</p> <button @click="paragraphClick">click</button> </template> <script> import { ref } from 'vue' import helperFunction from '@/utils/helperFunction' export default { props: { paragraphText: { type: String, default: 'i am the paragraph text' } }, setup(props) { const paragraphRef = ref(null) const paragraphClick = () => { if (paragraphRef.value) { helperFunction(paragraphRef.value, props.paragraphText, 0) } } return { paragraphRef, paragraphClick } } } </script>
辅助函数代码:
const helperFunction = (element, text, index) => { if (index === 0) { element.innerHTML = '' } element.innerHTML += text[index] if (index === text.length - 1) { return } setTimeout(() => helperFunction(element, text, index + 1), 100) } export default helperFunction
内容的提问来源于stack exchange,提问作者Ayoub Groubi
相关产品推荐
相关产品推荐

