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.

posted @ 2024-06-05 11:12  China Soft  阅读(322)  评论(0)    收藏  举报