【问题标题】:How to use global variables inside the setup Vuetify 3如何在设置 Vuetify 3 中使用全局变量
【发布时间】:2021-09-01 05:09:26
【问题描述】:

我正在使用 vue 3 设置,我想访问我使用的全局变量 vuetify。 我可以在 config.globalVariable 中看到它,但我无法在设置中使用它。

{_uid: 0, _component: {…}, _props: null, _container: div#app, _context: {…}, …}
component: ƒ component(name, component)
config: Object
compilerOptions: (...)
errorHandler: undefined
globalProperties:
$vuetify: {defaults: {…}}
$messageSystem: {addMessage: ƒ}
__proto__: Object
isNativeTag: (tag) => {…}
...

如您所见,我看到了 $vuetify,但在设置中我无法访问它。

    setup() {
       ...
       this.$vuetify.theme.dark = true; 
       ...

这是我访问全局变量的方式吗?

我得到的错误: Cannot read property '$vuetify' of undefined

【问题讨论】:

    标签: vue.js vuetify.js vuejs3 vue-composition-api vuetifyjs3


    【解决方案1】:

    您无法在setup 挂钩内访问this,但您可以使用getCurrentInstance 获取包含配置的应用实例:

    import { getCurrentInstance,onMounted } from 'vue'
    
    export default {
      setup() {
        const internalInstance = getCurrentInstance()
    
        onMounted(()=>{
          nternalInstance.appContext.config.globalProperties.$vuetify.theme.dark=true
       })
      }
    

    【讨论】:

    • 正是我需要的,谢谢!编辑:当我尝试在设置中登录internalInstace 时,它给了我null,因为某种原因我不在方法内执行const internalInstance = getCurrentInstance,我会做研究,但知道为什么它给null?
    • onMounted钩子里面试试onMounted(()=>{console.log(internalInstance)})
    猜你喜欢
    • 1970-01-01
    • 2020-10-24
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2013-08-16
    • 1970-01-01
    相关资源
    最近更新 更多