VUE项目创建之全局挂载 axios

1、vue2中全局挂载axios:

在vue2项目中,在入口文件main.js中通过Vue.prototype挂载全局方法对象。

import axios from 'axios'

//将包挂载到vue的原型对象上
Vue.prototype.$http = axios

vue3中全局挂载axios

vue3的基本使用(超详细)_luofei_create的博客-CSDN博客 

vue3中取消了Vue.prototype,需要使用官方提供的globalPropertiesAPI在全局挂载方法和属性。

// 引入使用axios
import axios from 'axios';
//将包挂载到vue的原型对象上
const app = createApp(App)
app.config.globalProperties.$http = axios;

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

2、使用全局变量

在vue2中使用:

vue2中使用this.$http , this.$qs

在vue3中使用:

在vue3的setup中是使用getCurrentInstanceAPI获取全局对象

//方法一
<script>
    import {useRouter} from 'vue-router';
    import {toRefs,getCurrentInstance} from 'vue';
    export default{
        setup(){
            const router = useRouter();
            const {proxy} = getCurrentInstance();
            const submit = () =>{
                proxy.$axios.post('/adminUser/login',{
                     userName:state.ruleForm.username || '',
                     passwordMd5:md5(state.ruleForm.password)
                 }).then(res=>{
                     console.log(res)
                 })
            }
            return{
                submit
            }
        }
        mounted(){
            this.submit()
        }
    }
</script>
 
.....
//方法二:
...
setup(){
    const currentInstance = getCurrentInstance()
    const {$axios,$route} = currentInstance.appContext.config.globalProperties
    function submit(){
        $axios.post('/adminUser/login',{
              userName:state.ruleForm.username || '',
              passwordMd5:md5(state.ruleForm.password)
        }).then(res=>{
               console.log(res)
       })
    }
}

通过getCurrentInstance()可以得到许多的全局对象。

总结
vue2中通过Vue.prototype来挂载全局对象,然后通过this.$XXX来获取全局对象。

vue3中通过app.config.globalProperties.$xxx = xxx来挂载全局对象,然后有两种方法来获取:

通过getCurrentInstance()方法获取上下文,这里的proxy就相当于this。例如:proxy.$axios
通过getCurrentInstance()方法获取当前实例,在根据当前实例找到全局实例对象appContext,进而拿到全局实例的config.galbalProperties。
 

日常记录,原文如下:

Vue全局挂载axios_禾木白的博客-CSDN博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值