欢迎微信关注Jerome blog,用技术的心去生活
一、使用公用模块
-
实现思路
首先定义一个专用的模块,用来组织和管理这些全局的变量,然后在需要使用的页面进行引入,从而实现全局变量。
-
代码示例
在 uni-app 项目根目录下创建 common 目录,然后在 common 目录下新建 helper.js 用于定义公用的方法。
const websiteUrl = 'http://uniapp.dcloud.io';
const now = Date.now || function () {
return new Date().getTime();
};
const isArray = Array.isArray || function (obj) {
return obj instanceof Array;
};
export default {
websiteUrl,
now,
isArray
}
接下来在 pages/index/index.vue 中引用该模块
<script>
import helper from '../../common/helper.js';
export default {
data() {
return {};
},
onLoad(){
console.log('now:' + helper.now());
},
methods: {
}
}
</script>
Tips:
- 维护方便,但是每次使用需要引入。
- 只支持多个vue页面或多个nvue页面之间公用,vue和nvue之间不公用。
二、挂载全局的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:' + this.now());
},
methods: {
}
}
</script>
Tips:
- 每个页面中不要在出现重复的属性或方法名。
- 只需要在 main.js 中定义好即可在每个页面中直接调用。
- 建议在 Vue.prototype 上挂载的属性或方法,可以加一个统一的前缀。比如 $url、global_url 这样,在阅读代码时也容易与当前页面的内容区分开。
- 注意这种方式只支持多个vue页面或多个nvue页面之间公用,vue和nvue之间不公用。