vue3.0 setup 中使用 globalProperties

// 2.0
Vue.prototype.$http = () => {}

// 3.0
const app = Vue.createApp({})
app.config.globalProperties.$http = () => {}

最常用的场景,在页面渲染前,通过http请求获取需要显示的数据。

在2.0,通过在vue原型上添加$http 属性,可以在组件实例中通过this.$http使用;

//2.0
 created(){
      this.$http.get('/getData').then().catch(err => {console.log(err)})
}

而在3.0的settup中是没有this的。

import { getCurrentInstance,onBeforeMount} from 'vue';
setup (props,context) {
      const {ctx } = getCurrentInstance();
      onBeforeMount(()=>{
        ctx.$http.get('/getData').then().catch(err => {console.log(err)})
      });
      .......
}
原文地址:https://www.cnblogs.com/gxp69/p/13902279.html