I can get component name in vue js 2 by: this.$options.name. How to get it in vue js 3?
Thank you.
I managed to get component name at runtime like this:
<script setup lang="ts">
import {getCurrentInstance} from 'vue'
const componentName = getCurrentInstance()?.type.__name
</script>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With