返回列表 发帖

Vue 3.0 自定义元素交互

#概览
非兼容:自定义元素白名单现在在模板编译期间执行,应该通过编译器选项而不是运行时配置来配置。
非兼容:特定 is prop 用法仅限于保留的 <component> 标记。
新增:有了新的 v-is 指令来支持 2.x 用例,其中在原生元素上使用了 v-is 来处理原生 HTML 解析限制。
#自主定制元素
如果我们想添加在 Vue 外部定义的自定义元素 (例如使用 Web 组件 API),我们需要“指示”Vue 将其视为自定义元素。让我们以下面的模板为例。

<plastic-button></plastic-button>
#2.x 语法
在 Vue 2.x 中,将标记作为自定义元素白名单是通过 Vue.config.ignoredElements:

// 这将使Vue忽略在Vue外部定义的自定义元素
// (例如:使用 Web Components API)
Vue.config.ignoredElements = ['plastic-button']
#3.x 语法
在 Vue 3.0 中,此检查在模板编译期间执行指示编译器将 <plastic-button> 视为自定义元素:

如果使用生成步骤:将 isCustomElement 传递给 Vue 模板编译器,如果使用 vue-loader,则应通过 vue-loader 的 compilerOptions 选项传递:
  // webpack 中的配置
  rules: [
    {
      test: /\.vue$/,
      use: 'vue-loader',
      options: {
        compilerOptions: {
          isCustomElement: tag => tag === 'plastic-button'
        }
      }
    }
    // ...
  ]
如果使用动态模板编译,请通过 app.config.isCustomElement 传递:
  const app = Vue.createApp({})
  app.config.isCustomElement = tag => tag === 'plastic-button'
需要注意的是,运行时配置只会影响运行时模板编译——它不会影响预编译的模板。

#定制内置元素
自定义元素规范提供了一种将自定义元素用作自定义内置模板的方法,方法是向内置元素添加 is 属性:

<button is="plastic-button">点击我!</button>
Vue 对 is 特殊 prop 的使用是在模拟 native attribute 在浏览器中普遍可用之前的作用。但是,在 2.x 中,它被解释为渲染一个名为 plastic-button 的 Vue 组件,这将阻止上面提到的自定义内置元素的原生使用。

在 3.0 中,我们仅将 Vue 对 is 属性的特殊处理限制到 <component> tag。

返回列表