全局挂载

vue2用法
在vue2中会习惯性的把axios挂载到全局,以方便在各个组件或页面中使用this.$http请求接口。但是在vue3中取消了Vue.prototype,在全局挂载方法和属性时,需要使用官方提供的globalPropertiesAPI。

import axios from 'axios'
// 配置请求的跟路径
axios.defaults.baseURL = 'http://127.0.0.1'
Vue.prototype.$http = axios

在vue3项目中,入口文件main.js配置globalProperties挂载全局方法对象

const app = createApp(App)

/* 挂载全局对象 start */
app.config.globalProperties.$http = Axios
/* 挂载全局对象 end */

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

全局使用

在vue2中全局使用:$http

<script>
  export default {
    data() {
      return {
        list: []
      }
    },
    mounted() {
      this.getList()
    },
    methods: {
      getList() {
        this.$http({
          url: '/api/v1/posts/list'
        }).then(res=>{
          let { data } = res.data
          this.list = data
        })
      },
    },
  }
</script>

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

<template>
  <div class="box"></div>
</template>
<script>
  import { ref, reactive, getCurrentInstance } from 'vue'
  export default {
    setup(props, cxt) {
      // 方法一 start
      const currentInstance = getCurrentInstance()
      const { $http, $message, $route } = currentInstance.appContext.config.globalProperties
      
      function getList() {
        $http({
          url: '/api/v1/posts/list'
        }).then(res=>{
          let { data } = res.data
          console.log(data)
        })
      }
      // 方法一 end

      // 方法二 start
      const { proxy } = getCurrentInstance()
      
      function getData() {
        proxy.$http({
          url: '/api/v1/posts/list'
        }).then(res=>{
          let { data } = res.data
          console.log(data)
        })
      }
      // 方法二 end

    }  
  }
</script>

方法一:通过getCurrentInstance方法获取当前实例,再根据当前实例找到全局实例对象appContext,进而拿到全局实例的config.globalProperties。
方法二:通过getCurrentInstance方法获取上下文,这里的proxy就相当于this。
提示: 可以通过打印getCurrentInstance()看到其中有很多全局对象,如: r o u t e 、 route、 routerouter、 s t o r e 。如果全局使用了 E l e m e n t U I 后,还可以拿到 store。如果全局使用了ElementUI后,还可以拿到 store。如果全局使用了ElementUI后,还可以拿到message、$dialog等等。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐