vue3 封装js中使用getCurrentInstance
封装 axios的时候,需要 用弹窗,这个弹窜调用必须用 getCurrentInstance
请问这个 怎么做呢。。
不知道你这个问题是否已经解决, 如果还没有解决的话:在Vue2的任何一个组件中想要获取当前组件的实例可以通过 this 来得到,而在Vue3中我们大量的代码都在 setup 函数中运行,并且在该函数中 this 指向的是 undefined,这时就需要使用getCurrentInstance
<template>
<div>
<p>{{ num }}</p>
</div>
</template>
<script>
import {ref, getCurrentInstance} from 'vue'
export default {
setup() {
const num = ref(3)
const instance = getCurrentInstance()
console.log(instance)
return {num}
}
}
</script>
可以看到 ctx 和 proxy 的内容十分类似,只是后者相对于前者外部包装了一层 proxy,由此可说明 proxy 是响应式的
在 Vue 3 中,getCurrentInstance 是一个 Composition API,可以在 setup 函数中使用。因此,封装 axios 并在弹窗中使用 getCurrentInstance,可以按照以下步骤进行:
1、创建一个包含 axios 的插件。
import axios from 'axios'
export default {
install: (app) => {
app.config.globalProperties.$http = axios
}
}
2、在需要使用弹窗的组件中,引入 getCurrentInstance 并使用 setup 函数。在 setup 函数中,可以使用 inject 方法将 $http 从全局配置中注入到组件中。然后,就可以在组件中使用 $http 发送请求,并在需要时使用 getCurrentInstance 弹出弹窗。
<template>
<button @click="handleClick">Click Me!</button>
</template>
<script>
import { getCurrentInstance, inject } from 'vue'
export default {
setup() {
const instance = getCurrentInstance()
const $http = inject('$http')
const handleClick = async () => {
const result = await $http.get('/api/data')
if (result.success) {
instance.appContext.config.globalProperties.$toast('Success!')
} else {
instance.appContext.config.globalProperties.$toast('Failed!')
}
}
return { handleClick }
}
}
</script>
在上述代码中,getCurrentInstance 用于获取当前组件实例,inject 用于从全局配置中注入 $http。然后,handleClick 函数中就可以使用 $http 发送请求,并根据返回值弹出不同的弹窗。