vue 中定义全局变量-挂载 Vue.prototype方式


将一些使用频率较高的常量或者方法,直接扩展到 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 这样,在阅读代码时也容易与当前页面的内容区分开。

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM