將一些使用頻率較高的常量或者方法,直接擴(kuò)展到 Vue.prototype 上瑞筐,每個(gè) Vue 對(duì)象都會(huì)“繼承”下來。
優(yōu)點(diǎn):只需要在 main.js 中定義好即可在每個(gè)頁面中直接調(diào)用。
注意:Vue 上掛載屬性的方式只支持vue
頁面拭宁,不能在 nvue頁面中使用。
示例如下:
- 在 main.js 中掛載屬性/方法
Vue.prototype.apiUrl = '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;
};
Vue.prototype.dosomething = function(){
console.log('do....');
}
- 在test.vue 中調(diào)用
<template>
<view>
當(dāng)前時(shí)間戳:{{time}}
</view>
</template>
<script>
export default {
data() {
return {
time:""
}
},
methods: {
},
onLoad:function(){
this.dosomething();
console.log("now:" + this.now());
this.time = this.now();
console.log("apiUrl :" + this.apiUrl);
}
}
</script>
<style>
</style>
建議:
- 每個(gè)頁面中不要再出現(xiàn)和全局變量(或方法)相同的屬性名(或方法名)。
- 在 Vue.prototype 上掛載的屬性或方法红淡,可以加一個(gè)統(tǒng)一的前綴不狮。比如 $url、global_url 這樣在旱,在閱讀代碼時(shí)也容易與當(dāng)前頁面的內(nèi)容區(qū)分開摇零。