1. 程式人生 > >前端公共模組的建立和使用

前端公共模組的建立和使用

在專案中,我們常常會用到一些可複用的全域性變數,如ip,時間,或者工具函式,如果在使用的時候去定義,建立,獲取,會使得程式碼變得冗餘。
所以,一個好的開發者應該首先一個好的共用模組。下面只是簡介一下。

首先,我們定義一個專用的模組,用來組織和管理這些全域性變數,並在需要的頁面進行引入。
一般我們會在src下建立一個common目錄,來存放共用模組的指令碼。然後在common目錄下新建一個common.js用於定義共用的方法。

common.js示例如下:

//定義一個全域性變數url
const url = "http://www.zhongmingyuan.com";
//定義一個工具方法,用於獲取當前時間
const now = Date.now || function(){
	return new Date().getTime();
}
const isArray = Array.isArray || function(obj){
	return obj instanceof Array;
}
export default {
	websiteUrl,
	now,
	isArray
}

方法一:模組引入
如果我們在接下來在index.vue中引入該模組(我這裡是vue專案,使用其他前端框架的專案也一樣的道理)

<script>
	import common form '../common/common.js';	//引入模組,並宣告模組名
	export default {
		data(){
			return {};
		},
		onLoad(){
			console.log("now:"+common.now());	//這裡使用模組函式
		}
	}
</script>

方法二:掛在Vue.prototype上
將一些使用頻率較高的常量或者方法,直接擴充套件到vue.prototype上,每個vue物件都會“繼承”下來。

例項如下:

//在main.js中掛載屬性/方法
Vue.prototype.websiteUrl = "http://uniapp.dcloud.io";
Vue.prototype.now = Date.now || function(){
	return new Date().getTime();
}
Vue.prototype.isArray = Array.isArray || function(obj){
	return obj instanceof Array;
}

然後在pages/index/index.vue中呼叫

<script>
	export default {
		data(){
			return {};
		},
		onLoad(){
			console.log("now:"+common.now());	//這裡使用模組函式
		}
	}
</script>