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>
.
Vue3 获取组件名称
获取方式:getCurrentInstance().type.__name
解读:Vue3 无法使用 this 关键字,但是官方提供了 getCurrentInstance()
方法来获取当前 Vue 组件实例对象,再通过 type
来获取 __name
组件名称。
<script setup>
import {getCurrentInstance, onMounted} from "vue"
onMounted(() => {
console.log(getCurrentInstance().type.__name)
})
</script>
.
⚠️ 其实通过 getCurrentInstance().ctx.$options.__name
也可以获取 Vue3 组件实例名称,但是比较复杂。
🥚 彩蛋:Vue3 获取组件的文件路径
获取方式:getCurrentInstance().type.__file
<script setup>
import {getCurrentInstance, onMounted} from "vue"
onMounted(() => {
console.log(getCurrentInstance().type.__file)
})
</script>
.
参考
分类:
前端 / Vue
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战