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

看了不少方法介紹,基本思路是,定義方法->在main.js中引入->就能全局使用,提升代碼的複用性。我這裏只寫下工做中常見和經常使用的方法html

使用export default + install + Vue.prototypevue

方法寫在哪,怎麼寫,通常按項目規則和我的習慣函數

我這裏以$http爲例學習

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

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

 

2.在main.js中寫入函數spa

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

3.在全部組件裏可調用函數prototype

this.$http(...);

 

 

數據綁定學習連接:https://www.jianshu.com/p/c02cb881bea8code

參考:htm

http://www.javashuo.com/article/p-rztszvui-dq.htmlblog

http://www.javashuo.com/article/p-aipofcll-dk.html

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

相關文章
相關標籤/搜索