Vue2,Vue3全局挂载

一、全局挂载 示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。

vue2中挂载全局 

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

import Vue from 'vue' 
import Axios from 'axios 
import utils from '@/utils' 
import qs from 'qs' ... //挂载全局对象 
Vue.prototype.$http = Axios; 
Vue.prototype.$qs = qs 
....

vue3中挂载全局   

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

import { createApp } from 'vue' 
import App from './App.vue' 
import router from './router/index' 
import axios from './utils/axios' 
import qs from 'qs' 

const app = createApp(App) //全局挂载 
app.config.globalProperties.$axios = axios; 
app.config.globalProperties.$qs = qs; 
...

二、使用全局 在vue2中使用  

vue2中使用

this.$http , 
this.$qs 
<script> 
    export default { 
        data() { 
              return { dataList: [] } 
        }, 
        mounted() { 
            this.getList() 
        }, 
        methods: {
             getList() { 
                this.$http({ url: 'url地址' }).then(res=>{ let { data } = res.data                                 
              this.dataList = data }) 
             }, 
        }, 
    } 
</script>

在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) }) 
    } 
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值