Craig
Craig

Reputation: 768

Vue composite make function reactive?

Is it possible to create a composite function such that consumer can provide a reference to a function? In mixins you could just call the consumer method as long as it existed. Here is how I would think this would work but it doesn't. method1 is not reactive. I realize this might be an antipattern. Sometimes you run an async/ajax call and once it's done it would be nice to just run the callback method1 instead of changing a dummy value and running a watch on it in the consumer. Ideas?

-- consuming component

setup() {
  let { prop1, method1, method2 } = useComposite();

  method1 = (o) =>
  {
    console.log(o);
  };

  method2();
}

composable function --

export default function useComposite()
{
  let method1 = ref(()=>{});
  const method2 = () => 
  {
    method1.value("hello");
  };
  const prop1 = ref(o);

  return {
   method1,
   methoid2,
   prop1,
  };
}

Upvotes: 0

Views: 752

Answers (1)

Estus Flask
Estus Flask

Reputation: 222309

method1 is already a ref and used as such. If it's redefined, this should be done like:

  method1.value = (o) => ...

This is definitely an antipattern. There could be multiple callbacks, while it's limited to one. A more complete solution could use event bus like mitt and register handlers for an event.

A proper solution with composition API would involve a watcher. Nothing requires composition API here. It's just callback-based control flow and a step back from promise-based one. If method2 is asynchronous, it needs to return a promise and be chained in a place it's used:

 const method1 = (o) => ...
 method2().then(method1);

Upvotes: 2

Related Questions