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)})
      });
      .......
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM