自定义元素

概览

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

自定义元素白名单

vue3中自定义元素检测发生在模板编译时,如果要添加一些vue之外的自定义元素,需要在编译器选项中设置isCustomElement选项

使用vue-cli构建工具时,模板都会用vue-loader预编译,设置它提供的compilerOptions选项: vue.config.js

 

 

 我们在vue.config.js文件中配置白名单

module.exports={
    chainWebpack:config=>{
        config.module
        .rule('vue')
        .use('vue-loader')
        .tap(options=>{
            options.compilerOptions={
                isCustomElement: tag => tag === 'barChart'
              }
              return options
        })

    }
}

 此时就不会弹出警告

使用vite,在vite.config.js中配置vueCompilerOptions

module.exports={
  vueCompilerOptions:{
    isCustomElement: tag => tag === 'barChart'
 }
}

 

  如果采用是是运行时编译版本的vue,可通过全局配置isCustomElement 

const app=Vue.createApp({})
app.config.isCustomElement=tag=>tag==="barChart"

 注意:运行时配置只会影响运行时模板编译,它不会影响预编译的模板

is属性仅限于用在component标签上

vue3中设置动态组件时,is属性仅仅能用于component标签上

在保留的<component>上使用时,它的行为与vue2.x中是完全相同

<component is="ren"></component>

在普通组件上使用时,它的行为将类似于普通的prop

<demo is="ren"/>  

vue2.x行为:渲染ren组件

vue3.x行为:通过is prop渲染demo组件

在普通元素上使用时,它将作为is选项传递给createElement调用,并作为原生attribute渲染,这支持使用自定义的内置元素

<button is="barChart">点击</button>

vue2.x行为:渲染barChart组件

vue3.x行为:通过回调渲染原生的button

dom内模板解析使用v-is指令代替

<table>
  <tr v-is="'table-row'"></tr>
</table>

 案例: 

创建tablerow.vue

<template>
    <div>
    <tr>
        <td>{{data}}</td>
    </tr>
    </div>
</template>
<script>
    export default {
        props:['data']
    }
</script>

 app.vue

<template>
   <div>
   <table>
     <tr v-is="'tableRow'" v-for="(item,index) in items" :key="index" :data="item"></tr>
   </table>
   </div>
</template>

<script>
import tableRow from "./components/tableRow.vue"
   export default {
      components:{
         tableRow
      },
      data(){
         return {
            items:[1,2,3]
         }
      }
   }
</script>

 

v-is像一个动态的vue2.x中的 :is绑定 ,因此要按注册名称渲染组件,其值应为JavaScript字符串文本

  <tr v-is="'tableRow'" v-for="(item,index) in items" :key="index" :data="item"></tr>

 

posted @ 2021-11-11 17:07  keyeking  阅读(297)  评论(0编辑  收藏  举报