You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js如何识别组件标记?<my-component>与MyComponent的关联机制是什么?

Vue组件识别机制详解

Let's tackle your two questions one by one—they get to the core of how Vue handles component registration and template parsing!

问题1:Vue.js如何知晓该标记是组件?

Vue maintains a registry of all components you've registered (either locally in a component's components option, or globally via Vue.component()). When it parses your template:

  • First, it checks if the tag is a native HTML element (like <div>, <p>, etc.).
  • If it's not a native tag, it looks up its internal component registry to see if there's a registered component that matches the tag name.

In your code example, you've locally registered MyComponent in the parent component's components option:

<template>
  <!-- Vue checks its registry and finds MyComponent matches this tag -->
  <my-component></my-component>
</template>

<script>
import MyComponent from '../MyComponent.vue'

export default {
  components: {
    MyComponent // 这一步就是把组件注册到当前组件的本地注册表中
  }
}
</script>

Once registered, Vue knows that <my-component> isn't a native element—it's a custom component you've defined, so it renders that component instead of treating it as an unknown HTML tag.

问题2:Vue.js如何识别<my-component>等同于MyComponent?

This is all about Vue's automatic case conversion between kebab-case and PascalCase, which solves a key mismatch between HTML and JavaScript:

  • HTML is case-insensitive, so tags like <MyComponent> get converted to lowercase <mycomponent> by browsers, which wouldn't match your PascalCase component name.
  • JavaScript uses PascalCase for component constructors (like your imported MyComponent) as a standard convention.

Vue bridges this gap by:

  1. When you register a component with a PascalCase name (like MyComponent), Vue automatically creates a kebab-case alias (my-component) for it.
  2. When parsing the template, it converts kebab-case tags to PascalCase to look up the component in the registry.

You can also explicitly register a component with a kebab-case name if you prefer:

components: {
  'my-component': MyComponent // 直接用kebab-case注册,模板里也用<my-component>
}

Either way, Vue handles the mapping behind the scenes so you can write templates that follow HTML conventions while keeping your JavaScript code clean with PascalCase component names.


内容的提问来源于stack exchange,提问作者sazr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:13:46