11 vue 自定义全局方法

//global.js
//
定义vu
e 全局方

 
// 定义vue 全局方法 建议自定义的全局方法加_ 以示区分
export default {
  install(Vue, options = {}) {
    // 全局方法1
    Vue.prototype._fn1 = function () {
      // console.log('f1')
    }
    // 全局方法2
    Vue.prototype._fn2 = function () {
      // console.log('fn2');

    }
    // 全局方法3 再次封装element.ui的$confirm的方法
    Vue.prototype._confirm = function (cue, tip, handleConfirm) {
      // 当第二个参数是回调函数
      if (typeof tip !== 'string') {
        handleConfirm = tip
        tip = '提示'
      }
      (cue, tip, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(handleConfirm)
        .catch(() => {
          this.$message.info("已取消");
        });
    }
  }
}
 
 
//将then改写为async await模式
 // 全局方法3 封装element.ui的$confirm方法
    Vue.prototype._confirm = async function (cue, tip, handleConfirm) {
      // 当第二个参数是回调函数
      if (typeof tip !== "string") {
        handleConfirm = tip;
        tip = "提示";
      }
      let res = '' //try-catch有作用域范围如果 res定义在里面,等下if判断就拿不到res
      try {
        res = await this.$confirm(cue, tip, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
      } catch (error) {
        this.$message.info('已取消')
      }
      if (res === 'confirm') handleConfirm()



2.main.js文件注入

// 定义全局方法
import global from './utils/global'
Vue.use(global)

3.use

在vue实例对象methods使用。

//例子1
deleteSelected() {
      this._confirm(
        "批量删除数据不可恢复,是否继续?",
        this.deleteSelectedComfirm
      );
    },
    deleteSelectedComfirm() {
      console.log(this.multipleSelection);
    }
 
//例子2 接受原始处理函数的参数
handleDelete(index, row) { 
    this._confirm("删除此条数据不可恢复,是否继续?", () => {
        this.handleDeleteConfirm(index, row);
      });
},
handleDeleteConfirm(index, row) {
    console.log("row: ", row);
    console.log("index: ", index);
 }

 

2 在vue 页面标签中使用。

 

 

 

常见Vue全局方法

export default {
  install(Vue, options = {}) {
    /**
     * 更优雅的捕获async await异常 
     * @param {Function} asyncFunc 异步函数
     * 使用:const [error,res]=await this._errorCaptured(asyncFunc) this vue实例的对象
     */
    Vue.prototype._errorCaptured = async function (asyncFunc) {
      try {
        const res = await asyncFunc()
        return [null, res]
      } catch (error) {
        return [error, null]

      }
    }

    /**
     * 深拷贝一个对象
     * @param {object} obj 
     * @returns {object} 返回一个深拷贝对象
     */
    Vue.prototype._deepCopy = function deepCopy(obj) {
      var cloneObj;
      //当输入数据为简单数据类型时直接复制
      if (obj && typeof obj !== 'object') {
        cloneObj = obj;
      }
      //当输入数据为对象或数组时
      else if (obj && typeof obj === 'object') {
        //检测输入数据是数组还是对象
        cloneObj = Array.isArray(obj) ? [] : {};
        for (let key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] && typeof obj[key] === 'object') {
              //若当前元素类型为对象时,递归调用
              cloneObj[key] = deepCopy(obj[key]);
            }
            //若当前元素类型为基本数据类型
            else {
              cloneObj[key] = obj[key];
            }
          }

        }
      }
      return cloneObj;

    }

    /**
     * 返回格式化后的时间字符串
     * @param {Date} date 
     * @param {String} fmt  "hh:mm:ss" "yyyy-MM-dd hh:mm:ss"
     * @return {String} 返回格式化后的字符串
     */
    Vue.prototype._dateFormatter = function (date, fmt = "yyyy-MM-dd hh:mm:ss") { // 
      var o = {
        "M+": date.getMonth() + 1, //月份   
        "d+": date.getDate(), //
        "h+": date.getHours(), //小时   
        "m+": date.getMinutes(), //
        "s+": date.getSeconds(), //
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
        "S": date.getMilliseconds() //毫秒   
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
      for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      return fmt;
    }
    /**
     * 千分号隔开数据
     * @param {number} value 
     * @returns {string}
     */
    Vue.prototype._toThousand = function (value) {
      return value.toString().replace(/(\d)(?=(?:\d{3})+$)/g, "$1,")
    }

  }
}

 

posted on 2020-06-12 20:10  章画  阅读(897)  评论(0编辑  收藏  举报

导航