Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

vue3 + typescript 中,定义了一个全局变量,获取该值时却总报错

// main.ts 文件
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

import './styles/main.scss'

const app = createApp(App)

app.use(store)
app.use(router)
app.mount('#app')

// 定义全局变量
app.config.globalProperties.$http = 'xxxxx'

在 home.vue 文件中引入 getCurrentInstance(),获取 vue 实例,通过该函数返回的 ctx,获取刚才定义的全局变量;
image.png

<!-- home.vue -->
<template></template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref, getCurrentInstance } from 'vue'

export default defineComponent({
  name: '',
  components: {},
  setup() {
    console.log(getCurrentInstance().ctx)    // 会报错,没有 ctx 属性
    const { ctx } = getCurrentInstance()    // 一旦使用解构定义 ctx 时,ctx 就会报错
    
    return {}
  }
})
</script>

不知是 typescript 的问题还是 vue 的问题,但是不知道怎么修改,望路过大佬指点。
image.png
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
import { getCurrentInstance } from 'vue'

const MyComponent = {
  setup() {
    const internalInstance = getCurrentInstance()

    internalInstance.appContext.config.globalProperties // access to globalProperties
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...