vue中is的作用和用法

一、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>
相关推荐
weixin_382395232 小时前
为小工厂量身打造:本地部署的物料管理系统带缺料计算
前端·制造
__zRainy__2 小时前
解决pnpm v10+不自动构建
前端·pnpm·工程化
猫猫不是喵喵.3 小时前
Vue3 Props 属性
前端·javascript·vue.js
醉城夜风~4 小时前
CSS元素显示模式(display)
前端·css
AI大模型-小华4 小时前
Codex 三方充值快速入门指南
java·前端·数据库·chatgpt·ai编程·codex·chatgpt pro
做前端的娜娜子7 小时前
同一链接实现 PC Web 与移动 H5 自适应
前端·掘金·金石计划
小帅不太帅7 小时前
架构没变、规模没变,DeepSeek V4 Flash 正式版凭什么暴涨 47 分?
前端·aigc·deepseek
jarvisuni7 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
卷福同学8 小时前
AI编程出海第二步:验证关键词能否做站
前端·人工智能·后端