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 {appContext: {config: {globalProperties: global}}} = getCurrentInstance();//3.0.11
    onBeforeMount(()=>{
      global.$http.get('/getData').then().catch(err => {console.log(err)}) });
      .......
    }

 

posted @ 2020-10-30 15:15  Jade_g  阅读(14410)  评论(3编辑  收藏  举报