乐闻世界logo
搜索文章和话题

How to get current component name in vue js 3.0

1个答案

1

In Vue 3, obtaining the current component's name can be achieved through various methods, depending on the approach you're using to write components (e.g., Options API, Composition API). Below are some examples illustrating how to retrieve the component name in different scenarios:

Using Options API

When using the Options API, you can access the current component's name via this.$options.name. This is a more traditional approach, which was also used in Vue 2.

javascript
<template> <div> Current component name: {{ componentName }} </div> </template> <script> export default { name: 'MyComponent', data() { return { componentName: this.$options.name } } } </script>

Using Composition API

When using Vue 3's recommended Composition API, you can retrieve the component name using the getCurrentInstance method. This method returns the current component instance, from which you can access various instance-related information, including the component name.

javascript
<template> <div> Current component name: {{ componentName }} </div> </template> <script> import { ref, getCurrentInstance } from 'vue'; export default { setup() { const instance = getCurrentInstance(); const componentName = ref(instance?.type.name); return { componentName } } } </script>

Note

  • The getCurrentInstance() method should be used with caution, as it is primarily designed for library developers or those working with advanced features. Official recommendations advise against over-reliance on this method in regular application development, as it may couple component logic with the structure of the component tree.
  • In production mode, component names may be modified by minification tools, so caution is advised when relying on component names for logical processing.

The above are some methods for obtaining the current component name in Vue 3. I hope this is helpful for you!

2024年11月21日 09:26 回复

你的答案