需求

项目中使用this.$message写了大量Message提示,此时想修改Message提示距离窗口顶部的距离为200px,查看文档发现需要对Message传入offset参数。

 解决方案一

可以直接全局修改Message提示框的样式,但这种只适用于一次只能弹出一个提示框的情况,如出现多个提示框,则所有提示框会重叠在一块。

public.css

.el-message {
  top: 200px !important;
}
main.js

import 'public.css';
解决方案二

由于提示太多,一个个修改太繁琐,所以选择重写this.$message。

查看element-ui源码怎么写的

['success', 'warning', 'info', 'error'].forEach(type => {
  Message[type] = options => {
    if (typeof options === 'string') {
      options = {
      //options参数只有message一个
        message: options
      };
    }
    options.type = type;
    return Message(options);
  };
});
我们只需要在源码的基础上传入offset参数就好了,代码如下:

main.js

import Vue from 'vue';
import { Message } from 'element-ui';
//定义一个新的Message方法,多传入一个offset参数
const $message = options => {
  return Message({
    ...options,
    offset: 200
  });
};
 
//重写方法,将offset写入options
['success', 'warning', 'info', 'error'].forEach(type => {
  $message[type] = options => {
    if (typeof options === 'string') {
      options = {
        message: options,
        offset: 200
      };
    }
    options.type = type;
    return Message(options);
  };
});
//将$message挂载到this上
Vue.prototype.$message = $message;
//不加这行代码运行this.$message.closeAll时会报错
Vue.prototype.$message.closeAll = Message.closeAll;
拓展内容,控制Message提示每次只能弹出一个

main.js

import Vue from 'vue';
import { Message } from 'element-ui';
//定义一个新的Message方法
let messageInstance = null;
const $message = options => {
    if(messageInstance) {
    //判断是否有提示框,有则关闭
        messageInstance.close();
    }
    messageInstance = Message(options);
    return messageInstance;
};
 
//重写方法
['success', 'warning', 'info', 'error'].forEach(type => {
    $message[type] = options => {
        if (typeof options === 'string') {
            options = {
                message: options
            };
        }
        options.type = type;
        return Message(options);
    };
});
//将$message挂载到this上
Vue.prototype.$message = $message;
Vue.prototype.$message.closeAll = Message.closeAll
————————————————
版权声明:本文为CSDN博主「卿本无忧」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_39998026/article/details/122193987

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐