uin-app简明uniapp教程微信小程序

uniapp—通过挂载 Vue.prototype来自定义并引用

2020-04-03  本文已影响0人  瑟闻风倾

将一些使用频率较高的常量或者方法,直接扩展到 Vue.prototype 上,每个 Vue 对象都会“继承”下来。
优点:只需要在 main.js 中定义好即可在每个页面中直接调用。
注意:Vue 上挂载属性的方式只支持vue页面,不能在 nvue页面中使用。

示例如下

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....');
}
<template>
    <view>
        当前时间戳:{{time}}
    </view>
</template>

<script>
export default {
    data() {
        return {
            time:""
        }
    },
    methods: {
        
    },
    onLoad:function(){
        this.dosomething();
        console.log("now:" + this.now());
        this.time = this.now();
    }
}
</script>

<style>

</style>

建议:

  • 每个页面中不要再出现和全局变量(或方法)相同的属性名(或方法名)。
  • 在 Vue.prototype 上挂载的属性或方法,可以加一个统一的前缀。比如 $url、global_url 这样,在阅读代码时也容易与当前页面的内容区分开。
上一篇 下一篇

猜你喜欢

热点阅读