Vue.js如何获取组件所使用的标签名
Great question! In Vue, components don’t automatically know the tag name they’re rendered with—since a single component can be registered under multiple names across your app. But there are a couple of solid ways to get this information depending on your needs.
Solution 1: Use the Internal _componentTag Property (Quick Fix)
Vue tracks the tag name used to register a component in an internal property called _componentTag. You can access it directly via this.$options._componentTag in your child component.
Update your edit-item.vue like this:
<template> <button @click="sayMyTagName"> what is my tag name </button> </template> <script> export default { props: { }, methods: { sayMyTagName:function() { console.log("my tag name is:", this.$options._componentTag); // Logs "editItem" } } } </script>
⚠️ Note: This is an internal property (marked with an underscore), so it’s not part of Vue’s public API. It works reliably in Vue 2, but might change in future versions. Use this for quick, one-off cases.
Solution 2: Pass the Tag Name as a Prop (Explicit & Future-Proof)
For a more robust approach, explicitly pass the tag name as a prop from the parent. This avoids relying on internal APIs and makes your code clearer.
First, update edit-item.vue to accept a tagName prop:
<template> <button @click="sayMyTagName"> what is my tag name </button> </template> <script> export default { props: { tagName: { type: String, required: true } }, methods: { sayMyTagName:function() { console.log("my tag name is:", this.tagName); // Logs "editItem" } } } </script>
Then, pass the prop when using the component in App.vue:
<template> <div id="app"> <editItem tagName="editItem" /> </div> </template> <script> import editItem from './edit-item.vue' export default { name: 'App', components: { editItem } } </script>
This method is ideal if you might register the same component under different tag names later—just pass the appropriate name each time.
内容的提问来源于stack exchange,提问作者user4254398

