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>
this.type is undefined.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>
$options.name no longer exists, nor does this.type.Managed to get it using: this.$parent.componentName.
<script lang="ts">
import {Options, Vue} from 'vue-class-component';
import HelloWorld from '@/components/HelloWorld.vue';
import {Prop} from "vue-property-decorator";
import {Product} from "@/store/models";
@Options({
components: {
HelloWorld,
},
mounted() {
this.$emit('init', this.$parent.componentName + ' mounted')
},
emits: ['init']
})
export default class Home extends Vue {
@Prop(Array) private readonly products!: Product[];
}
</script>
None of the above answers worked for me...
This works (called from inside the component you want the name of):
console.log(this.$.type.name)
name property.