How to expose a function
How to expose a function, so that, the project can directly call the function inside the web component
Hello, could you please elaborate on what you hope to accomplish?
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.
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.
Hi, can you create a https://stackblitz.com example that reproduce your issue, this would be a great stating point
@wbrowar ?
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() {
...
}
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
This is how I do it.
customElements.whenDefined('custom-component').then(() => {
const ele = customElements.get('custom-component')
if (ele) {
ele.prototype.myFn = myFn
}
})