简体   繁体   English

使用 Vue3 公开创建 Web 组件的方法

[英]Expose method creating a web-component using Vue3

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:我正在使用 VueJS 3 创建一个 web 组件,我想在组件上公开一个方法,允许用户执行如下操作:

  <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?我如何向 Vue Component Wrapper 指示 customMethod 将在组件外部可用?

In <script setup> , use the defineExpose() macro :<script setup>中,使用defineExpose()

<script setup>
const customMethod = () => {⋯}
      👇
defineExpose({ customMethod })
</script>

In the setup() hook, use the expose property of the context argument :setup()挂钩中,使用context参数的expose属性

<script>
export default {   👇
  setup(props, { expose }) {
    const customMethod = () => {⋯}
      👇
    expose({ customMethod })
  }
}
</script>

In the Options API, use the expose option :在选项 API 中,使用expose选项

<script>
export default {
     👇
  expose: ['customMethod'],
  methods: {
    customMethod() {⋯}
  }
}
</script>

Currently (as of Vue 3.2.31), the only way to access the custom element's exposed properties is through its _instance.exposed property:目前(从 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>

Since _instance is a private property, use this solution with caution, as the property could be renamed/removed in a future release.由于_instance是私有属性,请谨慎使用此解决方案,因为该属性可能会在未来的版本中重命名/删除。

demo ( <script setup> ) 演示( <script setup>

demo ( setup() hook) 演示( setup()挂钩)

demo (Options API) 演示(选项 API)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM