Vue2和Vue3获取组件名称

Vue 获取组件名称


Vue2 获取组件名称

获取方式:this.$options.name

解读:通过 Vue2 的 this 关键字,可以很容易地访问 Vue 组件实例对象身上的 $options 的 name 属性来获取组件名称。

<script>
export default {
  name: "Brand",
  mounted() {
    // Brand
    console.log(this.$options.name)
  }
}
</script>

image-20240528200148572.



Vue3 获取组件名称

获取方式:getCurrentInstance().type.__name

解读:Vue3 无法使用 this 关键字,但是官方提供了 getCurrentInstance() 方法来获取当前 Vue 组件实例对象,再通过 type 来获取 __name 组件名称。

<script setup>
import {getCurrentInstance, onMounted} from "vue"

onMounted(() => {
  console.log(getCurrentInstance().type.__name)
})
</script>

image-20240528200613299.

⚠️ 其实通过 getCurrentInstance().ctx.$options.__name 也可以获取 Vue3 组件实例名称,但是比较复杂。



🥚 彩蛋:Vue3 获取组件的文件路径

获取方式:getCurrentInstance().type.__file

<script setup>
import {getCurrentInstance, onMounted} from "vue"

onMounted(() => {
  console.log(getCurrentInstance().type.__file)
})
</script>

image-20240528201629632.



参考

  1. 关于Vue3获取当前组件实例的 getCurrentInstance 方法的补充 - 掘金 (juejin.cn).
posted @ 2024-05-28 20:48  软柠柠吖  阅读(208)  评论(0编辑  收藏  举报