关于javascript:vue3中自定义元素交互的非兼容变更

7次阅读

共计 1602 个字符,预计需要花费 5 分钟才能阅读完成。

vue3 中自定义元素交互的非兼容变更

自主定制元素

如果咱们先增加在 Vue 内部定义的自定义元素,如应用 Web 组件 API,咱们须要批示 Vue 将其视为自定义元素:

<plastic-button></plastic-button>
// 在 2.x 中,将标记作为自定义元素白名单是通过 Vue.config.ignoredElements
// 这将使 Vue 疏忽在 Vue 内部定义的自定义元素
// (例如:应用 Web Components API)
Vue.config.ignoredElements = ['plastic-button']
// 在 Vue3 中,此查看在模板编译期间执行批示编译器将 <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> 标签上
在保留的 <component> tag 上应用时,它的行为将与 2.x 中完全相同

  • 在一般组件上应用时,他的行为将相似于一般 prop
<foo is="bar" />
在 vue2 中,将会渲染 bar 组件
在 vue3 中,会通过 is 属性渲染 foo 组件
  • 在一般元素上应用时,它将作为 is 选项传递给 createElement 调用,并作为原生属性渲染
<button is="plastic-button"> 点击我!</button>
在 vue2 中,渲染 plastic-button 组件
在 vue3 中,渲染原生 button:document.createElement('button', { is: 'plastic-button'})

v-is 用于 DOM 内模板解析解决方案

仅影响间接在页面的 HTML 中写入 Vue 模板的状况,在 DOM 模板中应用时,模板受原生 HTML 解析规定的束缚

<!-- 2.x -->
<table>
  <tr is="blog-post-row"></tr>
</table>

<!-- 2.x -->
<!-- 随着 is 的行为变动,新的指令 v -is 用来解决当前情况 -->
<!-- 留神:v-is 函数像一个动静的 2.x :is 绑定——因而,要按注册名称渲染组件,其值应为 JavaScript 字符串文本 -->
<table>
  <tr v-is="'blog-post-row'"></tr>
</table>
<!-- v-is 绑定的是一个 Javascript 变量 -->
<!-- 不正确,不会渲染任何内容 -->
<tr v-is="blog-post-row"></tr>
<!-- 正确 -->
<tr v-is="'blog-post-row'"></tr>
正文完
 0