Vue3 : How to override function with the composition API?

Viewed 851

Let's say we have a compasable function like below:

// composable/useShareComp.ts
export function useShareComp() {
  const toto = "hey";
  const tata = ref(0);

  function utilMethod() {
    console.log("Util Méthod !!");
  }
  function mainMethod() {
    console.log("Main Méthod !!");
    console.log("should call the overriden or fallback to this utilMethod");
    utilMethod()
  }
  return { toto, tata,  utilMethod,  mainMethod };
};

Now, I have 2 components that will use the composable method. (I use the new 3.2 version)

// components/SharComp.vue

<template>
  <h1>share comp</h1>
  <p>{{toto}}</p>
  <p>{{tata}}</p>
  <button @click="mainMethod">call main method</button>
</template>

<script setup lang="ts">

import { useShareComp } from "@/composable/useShareComp";

const { toto, tata, mainMethod } = useShareComp();
</script>

So above if the mainMethod is called it will simply called the utilMethod and thus log "Util Méthod !!"

But now I want in another component to override the utilMethod like in the code below

// components/MyNewComp.vue

<template>
  <h1>MY NEW COMP</h1>
  <p>{{toto}}</p>
  <p>{{tata}}</p>
  <button @click="mainMethod">call main method</button>
</template>

<script setup lang="ts">

import { useShareComp } from "@/composable/useShareComp";

const { toto, tata, mainMethod } = useShareComp();

function utilMethod() { // it will not override the utilMethod
  console.log("Util Method but in the MyNewComp!");
}
</script

In the MyNewComp component, I want utilMethod to be overridden and thus when mainMethod is called, it should log the new console.log("Util Method but in the MyNewComp!"); from the overridden utilMethod. But I don't have any idea of how to do that as we could easily do with some natives classes (and/or with the vue-class-components library)

1 Answers

You could pass the utilMethod as callback with default logic and you could override it :

// composable/useShareComp.ts
function defaultUtilMethod() {
    console.log("Util Méthod !!");
  }
export function useShareComp(utilMethod=defaultUtilMethod) {
  const toto = "hey";
  const tata = ref(0);

  
  function mainMethod() {
    console.log("Main Méthod !!");
    console.log("should call the overriden or fallback to this utilMethod");
    utilMethod()
  }
  return { toto, tata,  utilMethod,  mainMethod };
};

and :

<script setup lang="ts">

import { useShareComp } from "@/composable/useShareComp";
function utilMethod() {
  console.log("Util Method but in the MyNewComp!");
}
const { toto, tata, mainMethod } = useShareComp(utilMethod);


</script

example using pure js

function a() {
  console.log("aaaaa")
}

function b(f = a) {
  console.log('bbbbbb')
  f();
}

function c() {
  console.log("cccc")
}
console.log('------default callback--------')
b(); //prints bbbbbb aaaaa
console.log('------overriding the callback--------')
b(c); //prints bbbbbb cccc

Related