簡體   English   中英

使用 Vue3 公開創建 Web 組件的方法

[英]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是私有屬性,請謹慎使用此解決方案,因為該屬性可能會在未來的版本中重命名/刪除。

演示( <script setup>

演示( setup()掛鈎)

演示(選項 API)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM