1.在main.js中挂载一个全局属性。拿axios举例
import App from './App.vue';
import axios from './http' //封装的axios方法
const app = createApp(App); //创建应用
app.config.globalProperties.$axios = axios;//全局挂载
app.mount('#app')
2.在组件中使用axios
2.1方法一,使用 proxy
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance() ;
proxy.$axios.post(url).then(res=>{})
2.2 方法二
import { getCurrentInstance } from 'vue'
const currentInstance = getCurrentInstance()
const { $axios} = currentInstance.appContext.config.globalProperties
$axios(url).post(res => {})
以上方法,就是在vue中注册使用全局属性的方法。
注意:
我们在获取Vue3中全局挂载的方法时会这么写:
const { ctx } = getCurrentInstance()
这里的ctx不是setup提供的ctx,打包后在生产环境下是获取不到的。不可使用。
3.在ts中使用axios
以上方法在ts中,会报 类型“ComponentInternalInstance | null”上不存在属性“proxy”的错误
以下分别对应两种方法,给出对应的解决方法
3.1方法一,proxy写法的解决方法
import { getCurrentInstance} from "vue";
import type { ComponentInternalInstance } from "vue";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
//此时直接使用proxy.$axios会提示proxy可能为null,因此需要添加?来过滤null
proxy?.$axios.post(url).then(res=> {})
添加完?后又报以下错误
解决方法为:在src
文件夹下创建一个如extendProperties.d.ts
的文件,内容如下:
import { ComponentCustomProperties } from "@vue/runtime-core";
declare module "@vue/runtime-core" {
interface ComponentCustomProperties {
$axios: proxy; // 这里填类型
}
}
// 必须导出,才能在其他文件中使用
export default ComponentCustomProperties;
至此,第一种方法解决完毕。
3.2.第二种解决方法
创建一个useCurrentInstance.ts的hook
import { getCurrentInstance } from "vue";
import type { ComponentInternalInstance } from "vue";
export default function useCurrentInstance() {
const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const globalProperties = appContext.config.globalProperties;
return {
globalProperties,
};
}
/*在组件中使用
import useCurrentInstance from "@/hooks/useCurrentInstance";
const { globalProperties } = useCurrentInstance();
globalProperties.$axios(url).then(res=>{})
*/