What is the component name used for?
A Vue component’s name is useful for:
- Recursively referencing itself in its own template
- Displaying the component tree in Vue DevTools
- Showing the component name in warning stack traces
- Letting
<KeepAlive>match components to cache via itsinclude/excludeprops
Should a component’s name match the file name?
I think a component’s name should match its file name, for these reasons:
- If the component name and file name don’t match, it creates extra mental overhead—you have to remember two names
- If the component name matches the file name, name collisions are less likely, because you can’t have two files with the same name in the same directory
- When you see an error in the browser or debug in Vue DevTools and want to locate a component, it’s usually easier to search the project by file name than to search for a name property in code
- In other frameworks like React, file names and component names (function names) are usually consistent as well
Why you shouldn’t manually define the name option
If the component name should match the file name anyway, what’s the downside of manually setting name?
First, it adds maintenance burden: when you rename the component file, you also have to remember to update the name.
Also, many people create new components by copying an existing one, and then forget to update the name. During debugging, you’ll find Vue DevTools showing a component name that doesn’t match the file you’re actually working on. Then you have to search the codebase for the component’s name option to fix it—pretty annoying.
I’ve run into this a lot at work, so I don’t think it’s a rare problem. Forgetting to update name has nothing to do with someone’s skill level. A good architecture or convention should avoid situations that are easy to get wrong.
When you use Single-File Components (SFCs), Vue can automatically infer the component name from the file name. So we only need to care about file names—we don’t need to manually define name.
The exception
There’s one exception: when the component is a directory, like components/button/index.vue. The auto-generated component name becomes index, but what we want is button or Button. In that case, we do need to define name manually.
Interestingly, Vue handles this case in Vue DevTools, but doesn’t handle other cases. To solve this, I wrote a plugin: vite-plugin-vue-define-options-name. It can infer a component’s name from the file name automatically, and it can also detect the “directory component” case.
Top comments (0)