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>
相关推荐
pe7er3 小时前
window管理开发环境篇 - 持续更新
前端·后端
We་ct4 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·javascript·算法·leetcode·typescript
陈随易8 小时前
有生之年系列,Nodejs进程管理pm2 v7.0发布
前端·后端·程序员
冰暮流星8 小时前
javascript之事件代理/事件委托
前端
@yanyu6669 小时前
登录注册功能-明文
vue.js·springboot
陈随易10 小时前
AI时代,你还在坚持手搓文章吗
前端·后端·程序员
里欧跑得慢12 小时前
17. Flutter Hero动画实现:让界面过渡更加优雅
前端·css·flutter·web
IT_陈寒12 小时前
Vue的这个响应式陷阱,我debug了一整天才爬出来
前端·人工智能·后端
cn_mengbei12 小时前
用React Native开发OpenHarmony应用:Reanimated共享元素过渡
javascript·react native·react.js
kyriewen13 小时前
前端测试:别为了100%覆盖率而写测试,那是自欺欺人
前端·javascript·单元测试