I am creating a web-component using VueJS 3, I want to expose a method on the component allowing the user to do something like this:
<custom-component id="x1" />
<script>
var component = document.getElementById("x1");
component.customMethod(); // as focus() method on native elements
</script>
If I define a method on the component, I can call the method inside the component. But the method is not available when I use it as a web-component.
//main.ts/js
import { defineCustomElement } from "vue"
import component from "./component.ce.vue"
const element = defineCustomElement(component );
customElements.define("custom-component ", element);
//component.ce.vue
const customMethod = () => { console.log("Executed"); }
How I can indicate to Vue Component Wrapper that the customMethod will be available outside the component?
CodePudding user response:
Only exposed properties can be accessible from the component reference.
In <script setup>
, use the defineExpose()
macro:
<script setup>
const customMethod = () => {⋯}