[英]Expose method creating a web-component using Vue3
我正在使用 VueJS 3 創建一個 web 組件,我想在組件上公開一個方法,允許用戶執行如下操作:
<custom-component id="x1" />
<script>
var component = document.getElementById("x1");
component.customMethod(); // as focus() method on native elements
</script>
如果我在組件上定義一個方法,我可以在組件內部調用該方法。 但是當我將它用作網絡組件時,該方法不可用。
//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"); }
我如何向 Vue Component Wrapper 指示 customMethod 將在組件外部可用?
在<script setup>
中,使用defineExpose()
宏:
<script setup>
const customMethod = () => {⋯}
👇
defineExpose({ customMethod })
</script>
在setup()
掛鈎中,使用context
參數的expose
屬性:
<script>
export default { 👇
setup(props, { expose }) {
const customMethod = () => {⋯}
👇
expose({ customMethod })
}
}
</script>
在選項 API 中,使用expose
選項:
<script>
export default {
👇
expose: ['customMethod'],
methods: {
customMethod() {⋯}
}
}
</script>
目前(從 Vue 3.2.31 開始),訪問自定義元素的公開屬性的唯一方法是通過其_instance.exposed
屬性:
<!-- example/index.html -->
<body>
<custom-component id="x1"></custom-component>
<script>
const el = document.getElementById('x1')
👇
el._instance.exposed.customMethod()
</script>
</body>
由於_instance
是私有屬性,請謹慎使用此解決方案,因為該屬性可能會在未來的版本中重命名/刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.