Search code examples
javascriptvue.jsvuejs3

vue 3 both helper and comosable functions return "is not a function"


Template Code:

<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 = () => {
        helperFunction(paragraphRef, props.paragraphText, 0)
      }

      return { paragraphRef, paragraphClick }
    }
  }
</script>

Helper Function Code:

const helperFunction = (element, text, index) => {
  if (index === 0) {
    element.innerHTML = ''
  }
  
  element.innerHTML += text[index]

  if (index === text.length - 1) {
    return
  }

  setTimeout(() => helperFunction(index + 1), 100)
}

export default { helperFunction }

Problem: Uncaught TypeError: helperFunction is not a function at Proxy.paragraphClick

I have tried a Composable Function using "watchEffect" and "unref" to track the paragraph element, but the same error occur


Solution

  • You should destruct your imported function :

    import { helperFunction } from '@/utils/helperFunction'
    

    You shoul also use named export in the helper file :

    export const helperFunction = (element, text, index) => {
      if (index === 0) {
        element.innerHTML = ''
      }
      
      element.innerHTML += text[index]
    
      if (index === text.length - 1) {
        return
      }
    
      setTimeout(() => helperFunction(index + 1), 100)
    }