user4815162342
user4815162342

Reputation: 1688

Vue 3 composition API with updating refs

I am passing a ref value to a composable function, updateableSetting. This has an initial value, settingA, but can be updated by the user. When updated, us it possible to have useFeature run again and return an updated feature value?

export default defineComponent({
  setup() {
    const updateableSetting = ref('settingA')
    const { feature } = useFeature(updateableSetting.value)
  }
})

Upvotes: 1

Views: 9945

Answers (2)

Farid
Farid

Reputation: 463

I had same problem when using composables in nuxt 3. In nuxt 3 new reactive state is available called useState. try useState instead of ref.
for more information see nuxt 3 document: useState nuxt3

Upvotes: 2

user10706046
user10706046

Reputation:

Sure. Use a computed property

import { ref, defineComponent, computed} from 'vue'

const useFeature = (initialRef) => {
  const feature = computed(() => initialRef.value + ' - I am always up to date!')
  return {
    feature
  }
}

export default defineComponent({
  setup() {
    const updateableSetting = ref('settingA')

    //make sure you don't pass .value here - pass the whole ref object instead
    const { feature } = useFeature(updateableSetting) 

    return { feature }
  }
})

If you mean "run a function everytime updatedValue changes", you can use

watch(
   [updatedValue], 
   () => {console.log('updatedValue changed! doing some calculations...')}
)

Upvotes: 1

Related Questions