由于默认的message的配置是通过options传进去的,但是并没有开放全局配置给用户,看message的源码发现默认是3s。
export default {
data() {
return {
visible: false,
message: '',
// 在构造器中配置的默认时长
duration: 3000,
type: 'info',
iconClass: '',
customClass: '',
onClose: null,
showClose: false,
closed: false,
verticalOffset: 20,
timer: null,
dangerouslyUseHTMLString: false,
center: false
};
},
}
并且可以从源码中看到,配置options是调用Message方法时传入的,若没有传入就会使用默认配置
// 通过Vue.extend生成构造函数
let MessageConstructor = Vue.extend(Main);
const Message = function(options) {
if (Vue.prototype.$isServer) return;
options = options || {};
if (typeof options === 'string') {
options = {
message: options
};
}
let userOnClose = options.onClose;
let id = 'message_' + seed++;
options.onClose = function() {
Message.close(id, userOnClose);
};
instance = new MessageConstructor({
data: options
});
instance.id = id;
if (isVNode(instance.message)) {
instance.$slots.default = [instance.message];
instance.message = null;
}
instance.$mount();
document.body.appendChild(instance.$el);
let verticalOffset = options.offset || 20;
instances.forEach(item => {
verticalOffset += item.$el.offsetHeight + 16;
});
instance.verticalOffset = verticalOffset;
instance.visible = true;
instance.$el.style.zIndex = PopupManager.nextZIndex();
instances.push(instance);
return instance;
};
['success', 'warning', 'info', 'error'].forEach(type => {
Message[type] = options => {
if (typeof options === 'string') {
options = {
message: options
};
}
options.type = type;
return Message(options);
};
});
所以,为了实现需求,我们在Vue.use(ElementUI)之前重写这一套方法
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
const messages = ['success', 'warning', 'info', 'error'];
messages.forEach(type => {
ElementUI.Message[type] = options => {
if (typeof options === 'string') {
options = {
message: options
};
// 默认配置
options.duration = 5000;
options.showClose = true;
}
options.type = type;
return ElementUI.Message(options);
};
})
Vue.use(ElementUI, { size: 'small' });