1. 公用模块
1.1 定义一个专用的模块,用来组织和管理这些全局的变量,在需要的页面引入
在 uni-app 项目根目录下创建 common 目录,然后在 common 目录下新建 util.js 用于定义公用的方法。
const baseUrl = 'https://ceshi2.dishait.cn/api/v1';
const nowTime = Date.now || function () {
return new Date().getTime();
};
export default {
baseUrl,
nowTime,
}
1.2 接下来在 pages/index/index.vue 中引用该模块
<script>
import helper from '../../common/util.js';
export default {
data() {
return {};
},
onLoad(){
console.log('nowTime:' + utils.nowTime());
},
methods: {},
}
</script>
小结:
优点:这种方式维护起来比较方便;
缺点:需要每次都引入;
2. 挂载 Vue.prototype
将一些使用频