vue-web-component-wrapper icon indicating copy to clipboard operation
vue-web-component-wrapper copied to clipboard

How to expose a function

Open HaydeeChi opened this issue 3 months ago • 8 comments

How to expose a function, so that, the project can directly call the function inside the web component

HaydeeChi avatar Sep 11 '25 01:09 HaydeeChi

Hello, could you please elaborate on what you hope to accomplish?

EranGrin avatar Sep 11 '25 08:09 EranGrin

Hello @EranGrin , thanks for the reply. My goal is to use a module developed in Vue3 web component in a Vue2 project. The Vue2 project has a button. When clicked, I want to trigger a method in web component to query data.

HaydeeChi avatar Sep 17 '25 06:09 HaydeeChi

Hi @EranGrin, my team and I are also using your library and ran into a similar situation. We want to be able to expose public methods/functions in our Vue component and then be able to create a Vue template ref in the consuming app that can call that method from the ref. It seems like slots and props are carried over just fine, but methods don't seem to be available in the output.

wbrowar avatar Sep 25 '25 15:09 wbrowar

Hi, can you create a https://stackblitz.com example that reproduce your issue, this would be a great stating point

EranGrin avatar Sep 25 '25 15:09 EranGrin

@wbrowar ?

EranGrin avatar Oct 06 '25 15:10 EranGrin

how about a low tech solution like writing a custom function to the global window and calling it later?

window.VUE_TRIGGER_FUNCTION_FROM_APP = function triggerSomething() {
...
}

EyMaddis avatar Oct 22 '25 07:10 EyMaddis

I found the way to achieve my goal, but I don't know if there's a better solution.

<template>
  <div ref="someElInTemplate">...</div>
</template>

<script lang="ts">
interface MyCoolHTMLElement extends HTMLElement {
  myCoolFunction: () => void;
}
</script>

<script setup lang="ts">
const someElInTemplate = ref<HTMLElement>();

function myCoolFunction() { }

onMounted(() => {
  const hostNode = (
    somElInTemplate.value?.getRootNode() as ShadowRoot | undefined
  )?.host as MyCoolHTMLElement;

  hostNode.myCoolFunction = myCoolFunction;
});
</script>

https://stackoverflow.com/questions/71331974/exposing-functions-on-a-vue-defined-web-component-custom-element

HaydeeChi avatar Oct 30 '25 09:10 HaydeeChi

This is how I do it.

customElements.whenDefined('custom-component').then(() => {
  const ele = customElements.get('custom-component')
  if (ele) {
    ele.prototype.myFn = myFn
  }
})

mariadb-ThienLy avatar Nov 03 '25 11:11 mariadb-ThienLy