Vue自定義函數掛載到全局方法


看了很多方法介紹,基本思路是,定義方法->在main.js中引入->就能全局使用,提高代碼的復用性。我這里只寫下工作中常見和常用的方法

使用export default + install + Vue.prototype

方法寫在哪,怎么寫,一般按項目規則和個人習慣

我這里以$http為例

1.創建request文件夾,創建index.js文件,寫入方法

const $http = function(...){ //全局方法最好用$開頭
    ...
}
export default vueHttp = {
    install(Vue){
        ...
        Object.defineProperty(Vue.prototype,'$http',{
            value:$http,
            writable:false
        })//這里使用了數據綁定的方法,下面給出學習鏈接
    }
}
export {$http}

 

2.在main.js中寫入函數

import http from '@/request'
Vue.use(http)
 

3.在所有組件里可調用函數

this.$http(...);

 

 

數據綁定學習鏈接:https://www.jianshu.com/p/c02cb881bea8

參考:

https://www.cnblogs.com/conglvse/p/10062449.html

https://www.cnblogs.com/linjiangxian/p/11457517.html

https://www.jianshu.com/p/8ec5e1233ffe


免責聲明!

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



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