2

I'm starting to use Vue 3 and composables. However, it seems that the computed properties that depends on variables (or computed properties) in other composables are not updating.

This is my first composable:

import { ref, computed } from 'vue'

export default function useSum1() {

  const num1 = ref(2)
  const num2 = ref(3)

  // Simple sum
  const sum1 = computed(() => num1.value + num2.value)

  return {
    num1,
    num2,
    sum1
  }

}

My second composable:

import { ref, computed } from 'vue'

export default function useSum2 () {

  const num3 = ref(4)
  const num4 = ref(1)

  const sum2 = computed(() => num3.value + num4.value)

  return {
    num3,
    num4,
    sum2,
  }

}

And my third composable, this one requieres sum1 and sum2 from the previous composables:

import { computed } from 'vue'
import useSum1 from './useSum1'
import useSum2 from './useSum2'

const { sum1 } = useSum1()
const { sum2 } = useSum2()

export default function useSum3() {

  // This doesn't update when sum1 or sum2 changes, but works the first time
  const sum3 = computed(() => sum1.value + sum2.value)

  return {
    sum3
  }

}

In App.vue:

import useSum1 from './composables/useSum1'
import useSum2 from './composables/useSum2'
import useSum3 from './composables/useSum3'

const { num1, num2 } = useSum1()
const { num3, num4 } = useSum2()
const { sum3 } = useSum3()

setTimeout(() => {
  num1.value = 3
}, 2500)

setTimeout(() => {
  num3.value = 5
}, 5000)

// sum3 is always 10, never updates

Thank you for any help.

Rich
  • 406
  • 6
  • 12
  • You are changing the values of the output variables num1 and num3. You should set num1 and num3 in app.vue as refs and rewrite the composable functions so they except num1 and num3 as an input like `const {num2} = useSum1(num1)` and only output num 2 and num4. – Gabe Jun 03 '22 at 13:18

0 Answers0