el-button源码解读1——为什么组件最外层套的是Vue内置组件Component

130 阅读1分钟

为什么组件最外层套的是Vue内置组件Component

image.png 在 Vue 里, 是一个内置组件,配合 :is 属性,可以动态决定真正渲染成什么标签/组件。

<component :is="tag" ...>

等价于:“我现在先不知道要用什么标签,等运行时根据 tag 的值来决定”。

看 use-button.ts 里 _props 的逻辑: image.png 这说明 Button 组件有一个 tag 的 prop(定义在 button.ts 里),常见用法:

  • 默认 tag = 'button' → 渲染成原生 ,带上 disabled、type 等属性。
  • 你也可以改成 tag="a" 或别的标签,比如用来做伪按钮的链接,这时候就不会再给你加 disabled 那些原生 button 属性。

如果不用 ,而是死写成 ,那就没法通过 prop 改变最外层标签类型了,组件的可扩展性会变差。

button.ts 里 tag 这个 prop 是怎么定义的?

image.png tag 是 Button 组件的一个 prop,用来指定“最外层要渲染成哪个标签/组件”, 默认值button

结合刚才看到的模板:

<component
    :is="tag"
    ref="_ref"
    v-bind="_props"
    :class="buttonKls"
    :style="buttonStyle"
    @click="handleClick"
  >
</component>    
  • 当你写  → tag 是字符串 'a' →  渲染成 ...
  • 如果有高级用法,传入一个组件对象,也可以用 Button 的样式包一层别的组件

总结一下“从 prop 到渲染”的链路

  1. button.ts 定义 tag prop,默认 'button'
  2. const props = defineProps(buttonProps) → 得到 props.tag。
  3. useButton(props, emit) 里,用 props.tag 决定 _props(如果是 'button' 就加上 disabled、type 等)。
  4. 模板里  根据 tag 真实渲染成对应标签。