返回介绍

六、与自定义元素的互操作性

发布于 2024-04-04 21:33:24 字数 3307 浏览 0 评论 0 收藏 0

  • 非兼容:检测并确定哪些标签应该被视为自定义元素的过程,现在会在模板编译期间执行,且应该通过编译器选项而不是运行时配置来配置。
  • 非兼容:特殊的 is attribute 的使用被严格限制在保留的 <component> 标签中。
  • 新增:为了支持 2.x 在原生元素上使用 is 的用例来处理原生 HTML 解析限制,我们用 vue: 前缀来解析一个 Vue 组件。

自主定制元素

想要在 Vue 外部定义添加自定义元素 (例如使用 Web Components API),则需要“指示”Vue 将其视为自定义元素。让我们以下面的模板为例。

<plastic-button></plastic-button>

Vue 2.x

在 Vue 2.x 中,通过 Vue.config.ignoredElements 将标签配置为自定义元素:

// 这将使 Vue 忽略在其外部定义的自定义元素
// (例如:使用 Web Components API)

Vue.config.ignoredElements = ['plastic-button']

Vue 3.x

在 Vue 3.0 中,此检查在模板编译期间执行。要指示编译器将 <plastic-button> 视为自定义元素:

  • 如果使用构建步骤:给 Vue 模板编译器传入 isCustomElement 选项。如果使用了 vue-loader ,则应通过 vue-loadercompilerOptions 选项传递:

    // webpack 中的配置
    rules: [
      {
        test: /\.vue$/,
        use: 'vue-loader',
        options: {
          compilerOptions: {
            isCustomElement: tag => tag === 'plastic-button'
          }
        }
      }
      // ...
    ]
    
  • 如果使用动态模板编译,请通过 app.config.compilerOptions.isCustomElement 传递:

    const app = Vue.createApp({})
    app.config.compilerOptions.isCustomElement = tag => tag === 'plastic-button'
    

定制内置元素 is 属性

在 3.0 中,我们将 Vue 对 is attribute 的特殊处理限制在了 <component> 标签中。

  • 在保留的 <component> 标签上使用时,它的行为将与 2.x 中完全相同;

  • 普通组件上使用时,它的行为将类似于普通 attribute:

    <foo is="bar" />
    
    • 2.x 的行为:渲染 bar 组件。
    • 3.x 的行为:渲染 foo 组件,并将 is attribute 传递给它。
  • 普通元素上使用时,它将作为 is attribute 传递给 createElement 调用,并作为原生 attribute 渲染。这支持了自定义内置元素的用法。

    <button is="plastic-button">点击我!</button>
    
    • 2.x 的行为:渲染 plastic-button 组件。

    • 3.x 的行为:通过调用以下函数渲染原生的 button

      document.createElement('button', { is: 'plastic-button' })
      

使用 vue: 前缀来解决 DOM 内模板解析 问题

一些 HTML 元素,例如 <ul><ol><table><select> 对它们内部可以出现的元素有限制,以及一些像 <li><tr> 、和 <option> 只能出现在特定的其他元素中。

Vue 2.x

在 Vue 2 中,在原生标签上使用 is attribute 来绕过这些限制:

<table>
  <tr is="blog-post-row"></tr>
</table>

Vue 3.x

将元素解析为 Vue 组件需要添加一个 vue: 前缀:

<table>
  <tr is="vue:blog-post-row"></tr>
</table>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文