如何在Vue SFC的<script setup>语法中访问原this关键字的属性
在 <script setup> 语法下不存在组件实例this,你可以通过以下两种方式访问原挂载在this上的全局属性:
方案1:使用Vuetify官方提供的组合式API(推荐)
Vuetify 3 专门为组合式API场景提供了useVuetify工具方法,直接调用即可获取vuetify实例:
<script setup lang="ts"> import { useVuetify } from 'vuetify' const vuetify = useVuetify() // 直接访问主题色 const primaryColor = vuetify.themes.light.colors.primary </script>
该方案自带完善的Typescript类型支持,不需要额外做类型声明,是优先选择的方案。
方案2:通用全局属性访问方案
如果是自定义挂载到Vue全局的属性(比如自己挂载的$http、$utils等),可以使用Vue官方提供的getCurrentInstance方法获取组件实例代理:
<script setup lang="ts"> import { getCurrentInstance } from 'vue' const instance = getCurrentInstance() // 访问$vuetify const vuetify = instance?.proxy?.$vuetify const primaryColor = vuetify?.themes.light.colors.primary </script>
如果需要完善Typescript类型提示,可以在项目的类型声明文件(通常为shims-vue.d.ts或env.d.ts)中扩展全局属性类型:
declare module '@vue/runtime-core' { interface ComponentCustomProperties { $vuetify: import('vuetify').Vuetify // 其他自定义全局属性也可以在这里声明 } }
注意:
getCurrentInstance只能在setup函数或者Vue生命周期钩子中调用,不能在异步方法、普通工具函数中随意调用。
内容的提问来源于stack exchange,提问作者Peshang Hiwa
相关产品推荐
相关产品推荐

