將一些使用頻率較高的常量或者方法,直接擴展到 Vue.prototype 上,每個 Vue 對象都會“繼承”下來。
注意這種方式只支持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:' + this.now());
},
methods: {
}
}
</script>
這種方式,只需要在 main.js 中定義好即可在每個頁面中直接調用。
注意:
每個頁面中不要在出現重復的屬性或方法名。
建議在 Vue.prototype 上掛載的屬性或方法,可以加一個統一的前綴。比如 $url、global_url 這樣,在閱讀代碼時也容易與當前頁面的內容區分開。