vue设置全局变量和公共方法

  • 1.全局变量

      1)新建globalVariable.js
      const servicePort = '8088'
      export default {
      	servicePort
      }
      
      2)main.js中引入并挂在原型上
      import globalVariable from '@/pub/js/globalVariable'
      Vue.prototype.GLOBAL = globalVariable
      
      3)vue页面中使用
      this.GLOBAL.servicePort
    
  • 2.全局方法

      1)新建util.js
      export default {
      	dateFmtYMDHMS: function (dateO) { //时间格式化
          var result = "";
          if (dateO != null && dateO != "") {
            if (!(typeof dateO.time === "undefined")) {
              dateO = new Date(dateO.time);
            }
            var year = dateO.getFullYear();
            var month = dateO.getMonth() + 1 < 10 ? "0" + (dateO.getMonth() + 1) : dateO.getMonth() + 1;
            var currentDate = dateO.getDate() < 10 ? "0" + dateO.getDate() : dateO.getDate();
      
            result = year + "-" + month + "-" + currentDate + " " + (dateO.getHours() > 9 ? dateO.getHours() : "0" + "" + dateO.getHours()) + ":" + (dateO.getMinutes() > 9 ? dateO.getMinutes() : "0" + "" + dateO.getMinutes()) + ":" + (dateO.getSeconds() > 9 ? dateO.getSeconds() : "0" + "" + dateO.getSeconds());
          }
          return result;
        }
      }
      
      2.main.js引入并挂载到原型上
      import util from '@/pub/js/util'
      Vue.prototype.util = util
      
      3.vue页面中调用方法
      this.util.dateFmtYMDHMS
    

你可能感兴趣的:(前端)