Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current component name in vue js 3.0

Tags:

vuejs3

I can get component name in vue js 2 by: this.$options.name. How to get it in vue js 3?

Thank you.

like image 585
user657009 Avatar asked Jan 19 '26 08:01

user657009


2 Answers

I managed to get component name at runtime like this:

<script setup lang="ts">
import {getCurrentInstance} from 'vue'

const componentName = getCurrentInstance()?.type.__name
</script>
like image 103
eightball Avatar answered Jan 21 '26 02:01

eightball


Options API (IndexPageOptions.vue)

    <script>
    export default {
      name: 'IndexPageOptions',
      // created
      created () {
        console.log(this.$options.name + ': created')
      },
      mounted () {
        console.log(this.$options.name + ': mounted')
      }
    }
    </script>

Composition API (IndexPageComposition.vue)

    <script>
    // Imports
    import { defineComponent, onMounted, getCurrentInstance } from 'vue'
       
    export default defineComponent({
      name: 'IndexPageComposition',
      setup () {        
        // Created
        console.log(getCurrentInstance().type.name + ': created')
    
        onMounted(() => {
          console.log(getCurrentInstance().type.name + ': onMounted')
        })
      }
    })
    </script>

Script Setup (IndexPageScriptSetup.vue)

    <script setup>
    import { onMounted, getCurrentInstance } from 'vue'
    // Created
    console.log(getCurrentInstance().type.__name + ': created')
    
    onMounted(() => {
      console.log(getCurrentInstance().type.__name + ': onMounted')
    })
    </script>
like image 42
Horacio Labory Avatar answered Jan 21 '26 02:01

Horacio Labory



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!