首页 > 其他 > 详细

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

时间:2021-01-05 10:40:12      阅读:152      评论:0      收藏:0      [点我收藏+]
将一些使用频率较高的常量或者方法,直接扩展到 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 这样,在阅读代码时也容易与当前页面的内容区分开。

  

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

原文:https://www.cnblogs.com/cocoaguo/p/14233929.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!