[Vuejs]-Call anonymous function composable in other component vuejs 3

0👍

i resolve my question with this code:

first in my component:

call to my function ref

getCall(toRef(param_search,'param_search'))

in my composable add onMounted and watch

onMounted(() => {
        if (param_search) {
            getCall(param_search)
        }
    })
    watch(
        () => param_search,
            (val) => {
                if (val) {
                loading.value = true
                getCall(val)
            }
        },
    )

with this, i can access to my function

1👍

I think what you are trying to do is to use the composable in your child component, and then use template refs to pass the result around. IMO it does not make sense to use a composable that way, and I would try to avoid using template refs in general.

Looking at your code, the issue seems to be that the functions from the composable change the calls ref, and you have to make sure that both parent and child component use functions that alter the same calls ref. A way to do this is to use provide/inject inside the composable. Then you can setup the provide in the parent component, and inject the ref into any component that needs it.

You code doesn’t even need to change much. This is what the composable could look like:

import { provide, inject } from 'vue'

const callsSymbol = Symbol.for('calls-api-variable') // <---- create a symbol for the injection

export function createCallsApi(){
  const calls = ref([])
  const pagination = ref([])

  const getCall = async (param_search) => {...} 
  const deleteCall = (id) => ...
  const queryForKeywords = async (event) => {...};
  const getResults = async (page) => {...};
  const getItems = async (page) => {...};

  const callsApi = {
    calls,
    getCall,
    deleteCall,
    queryForKeywords,
    getResults,
    getItems
  } 

  provide(callsSymbol, callsApi) // <----- add a provide
  return callsApi
}

export function useCallsApi(){ // <---- composable to resolve the inject
  const callsApi = inject(callsSymbol)
  if (!callsApi) throw new Error('Failed to inject callsApi. Did you call createCallsApi() in a parent component?')
  return callsApi
}

With that, in your parent, you do

const { calls, getCall,...} = createCallsApi()

and in the child:

const { calls, getCall,...} = useCallsApi()

And that’s all, no fumbling around with template refs.

Does that work for you, does it make sense?

Leave a comment