Vue---Vue.use(param)的使用

Vue.use(param)后会自动执行param的install()方法。通过Vue.use(param)来封装一个工具类。

util.js

//工具类


let util = {};
util.install = function(Vue){
    //Message       type:消息类型(必传) message:消息内容(必传)
    Vue.prototype.$showMsg = (type, message) => {
        Vue.prototype.$message({
            type: type,
            message: message
        });
    }

    //Message Box    hintText:提示消息具体内容(必传)  callback:点击确定后的回调函数(必传)   cancel:点击取消后的回调(非必传)
    Vue.prototype.$showConfirm = (hintText, callback, cancel) => {
        Vue.prototype.$confirm(hintText, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            callback();
        }).catch(() => {
            if (cancel) {
                cancel();
            }
            Vue.prototype.$showMsg('info', '取消操作!');
        });
    }
    

   //下载文件处理工具 :  responase:接口返回的整体数据  fileName(非必传):自定义的文件名,例:xx.xlsx,如果没传,就用原文件名
    Vue.prototype.$download = (response,fileName) => {
        const originalFileName = decodeURI(response.headers['content-disposition'].split('filename=')[1]); // 原文件名
        const blob = new Blob([response.data], { type: 'application/octet-stream'});                       // 将二进制流转为Blob对象
        //利用h5超链接a的download属性进行下载文件
        const eLink = document.createElement('a');                                                             
        eLink.style.display = 'none';
        eLink.href = window.URL.createObjectURL(blob);
        eLink.download = (fileName == null || fileName == '') ? originalFileName : fileName;               //有传fileName,就用fileName
        document.body.appendChild(eLink);                                                    
        eLink.click();
        document.body.removeChild(eLink);
        window.URL.revokeObjectURL(blob);                                                                   //释放
    }

    
    //深拷贝
    Vue.prototype.$deepClone = (target) => {
        let result;
        if (typeof target === 'object') {       //对象类型
            if (Array.isArray(target)) {        //数组
                result = []; 
                for (let i in target) {
                    result.push(Vue.prototype.$deepClone(target[i]))
                }
            } else if(target===null) {          //null
                result = null;
            } else if(target.constructor===RegExp){
                result = target;
            }else {
                result = {}; 
                for (let i in target) {
                    result[i] = Vue.prototype.$deepClone(target[i]);
                }
            }
        } else {                                 //基本数据类型
            result = target;
        }
        return result;
    }

   


}


export default util

main.js中安装util

import Util from '@/utils/util.js'
Vue.use(Util)

页面中使用

this.$showConfirm('进入Home页面',() => {alert(11)});

猜你喜欢

转载自blog.csdn.net/qq_39115469/article/details/110917838