【问题标题】:How to wrap JS library which creates elements by itself into Vue component with slot?如何将自己创建元素的JS库包装到带slot的Vue组件中?
【发布时间】:2022-12-03 17:09:23
【问题描述】:

我有 vanilla JS 库,它被赋予了根元素和回调函数(data: any) => HTMLElement。库调用回调并在根元素中定位元素。

我想将这个库包装到带插槽的 Vue 组件中,以便像这样使用它:

<my-component v-slot='data'>
  <div>{{data.field}}</div>
</my-component>

useSlots 返回的插槽是被调用时返回虚拟 DOM 的函数。我怎样才能把它变成真正的 DOM 元素保留反应性?

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    听起来您想创建一个自定义 Vue 组件,该组件使用普通 JavaScript 库在组件内创建元素。为此,您可以使用 Vue.component() 方法创建一个自定义 Vue 组件,然后在该组件的 render 函数中使用该库。

    这是一个如何工作的示例:

    Vue.component('my-component', {
      render: function (createElement) {
        // Use the createElement function to create a root element for the component
        let root = createElement('div');
    
        // Use the vanilla JS library to create elements within the root element
        let elements = myLibrary(root, (data) => {
          return createElement('div', data.field);
        });
    
        // Return the root element with the generated elements as children
        return root;
      }
    });
    

    上面的代码将创建一个名为 my-component 的自定义 Vue 组件,它使用 myLibrary 函数在组件内生成元素。然后,您可以像这样在 Vue 应用程序中使用该组件:

    <my-component>
      <!-- Use the slot to provide a template for the generated elements -->
      <template v-slot="data">
        <div>{{data.field}}</div>
      </template>
    </my-component>
    

    这将使用提供的模板呈现由 myLibrary 函数生成的元素。生成的元素将是反应性的,因此对数据的任何更改都将反映在呈现的元素中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 2021-12-16
      • 2021-08-11
      • 1970-01-01
      • 2019-03-04
      • 2021-07-01
      • 1970-01-01
      • 2020-07-02
      相关资源
      最近更新 更多