Reputation: 782
I can get component name in vue js 2 by: this.$options.name. How to get it in vue js 3?
Thank you.
Upvotes: 15
Views: 9606
Reputation: 11
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>
Upvotes: 1
Reputation: 83
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)
Upvotes: 0
Reputation: 1230
I managed to get component name at runtime like this:
<script setup lang="ts">
import {getCurrentInstance} from 'vue'
const componentName = getCurrentInstance()?.type.__name
</script>
Upvotes: 6
Reputation: 52
import { useRouter } from "vue-router";
In setup,
const router = useRouter();
const componentName = router.currentRoute.value.name;
Upvotes: -1
Reputation: 782
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>
Upvotes: 0