skip to Main Content

I have seen many times how people wrap their function in a computed property to be able to call it with any value.

Here is an example

<template>
  {{ myComputedFunction(2) }}
</template>

<script setup lang="ts">
const refVariable = ref(5)

const myFunction = (a: number) => {
  return a * refVariable.value
}

const myComputedFunction = computed(() => myFunction)

setTimeout(() => {
  refVariable.value = 10
}, 5000)
</script>

Yes, at first the function will return 10, and after 5 seconds it will return 20. But how right is it to do this?

2

Answers


  1. This is a workable approach but it doesn’t serve a good purpose. A parametrized computed can be used to cache a function. Since creating new functions is fast in modern JS engines, and proxies that are used by computeds are relatively slow, this primarily makes sense if this involves some computations outside a function that are based on reactive values:

    const myComputedFunction = computed(() => {
      // some expensive preliminary computation
    
      return (a: number) => ...
    )
    

    Since myFunction is not reactive value, myComputedFunction is computed only once, myComputedFunction.value === myFunction. There’s no practical difference between {{ myComputedFunction(2) }} and {{ myFunction(2) }}.

    Login or Signup to reply.
  2. I’m agree with Boussadjra Brahim’s comment. its absolutely correct.

    first time: 2 * refVariable(5) = 10

    after 5 seconds refVariable value changes to 10, so your computed property will be called again.(computed property will be called every time, one of their dependencies changes.)

    second time: 2 * refVariable(10) = 20

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search