在vue項(xiàng)目開發(fā)中需要將一些通用方法或組件掛載到全局上,那么有幾種情況如下:
1.利用Vue的directive
添加自定義指令
<div id="app">
<input type="text" v-focus/>
</div>
main.js中
Vue.directive('focus', {
inserted: function (el,bind) {
el.focus();
}
2.在main.js中將函數(shù)擴(kuò)展到vue實(shí)例上
Vue.prototype.httpData = function (){
alert('執(zhí)行成功');
}
在其他組件中調(diào)用
this.httpData();
3.在main.js中引入自己寫好的文件http.js
http.js文件中
exports.install = function (Vue) {
Vue.prototype.http = function (){
alert('執(zhí)行成功');
};
};
main.js中
import http from './http'
Vue.use(http);
在其他組件中調(diào)用
this.http();
我的需求是將所有接口放在http.js中統(tǒng)一管理待讳,所以用的第三種方式告希,還遇到一個(gè)小問(wèn)題
image.png
當(dāng)我的文件名為http.js時(shí),會(huì)報(bào)一個(gè)錯(cuò)誤:
Uncaught ReferenceError: exports is not defined
image.png
但我把http.js重命名之后又不報(bào)了牍戚,原因在于babel中的.babelrc文件
"modules": false => "modules": true
岩榆,需要注意
{
"presets": [
["env",
{ "modules": true }
]]
}