一、is 的核心作用
1. 解决 HTML 原生标签的解析限制(最常见场景)
HTML 中有一些原生标签(如 <ul>/<ol>/<table>/<select>)对直接嵌套的子标签有严格限制:
<ul>只能包含<li><table>只能包含<tr>/<tbody>等<select>只能包含<option>/<optgroup>
如果直接在这些标签内使用 Vue 自定义组件(比如 <my-li>),浏览器会因为解析规则错误,导致组件渲染异常、样式失效或功能异常。此时通过 is 属性可以让 Vue 正确识别组件,同时满足 HTML 语法规范。
示例:解决 <table> 标签的嵌套限制
<template>
<!-- 错误写法:<table> 内直接写自定义组件,浏览器解析会出错 -->
<table>
<!-- <my-tr></my-tr> 这种写法会被浏览器当作无效标签,渲染异常 -->
</table>
<!-- 正确写法:用 is 指定自定义组件 -->
<table>
<!-- <tr> 是符合 <table> 规范的标签,通过 is 告诉 Vue 渲染 my-tr 组件 -->
<tr is="my-tr"></tr>
</table>
</template>
<script>
export default {
components: {
MyTr: {
template: '<td>这是自定义的表格行</td>'
}
}
}
</script>
2. 实现动态组件(核心功能)
通过 is 绑定一个变量,可以动态切换要渲染的组件,实现 "一个容器渲染不同组件" 的效果,是 Vue 实现组件切换的极简方案。
示例:动态切换组件
<template>
<div>
<!-- 按钮切换组件 -->
<button @click="currentComponent = 'componentA'">显示组件A</button>
<button @click="currentComponent = 'componentB'">显示组件B</button>
<!-- 核心:通过 is 动态绑定要渲染的组件名 -->
<component :is="currentComponent"></component>
</div>
</template>
<script>
export default {
data() {
return {
// 默认显示 componentA
currentComponent: 'componentA'
}
},
components: {
ComponentA: {
template: '<div>我是组件A</div>'
},
ComponentB: {
template: '<div>我是组件B</div>'
}
}
}
</script>
动态组件切换时,若想保留组件状态(比如输入框内容),需配合 <keep-alive> 使用:
<keep-alive>
<component :is="currentComp"></component>
</keep-alive>