看了很多方法介紹,基本思路是,定義方法->在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
