前言
最近的 coreui/vue 后台管理的项目中默认引入的是 vue-notification + mini-toastr 的消息提示,使用起来比着 element ui 麻烦一些,一开始翻了文档也没找到如何定义到全局。就每个文件重复定义。直到这两天突然有了灵感给解决了。
main.js 中初始化
import VueNotifications from "vue-notifications";
import miniToastr from "mini-toastr"; // https://github.com/se-panfilov/mini-toastr
// notifications
const toastTypes = {
success: "success",
error: "error",
info: "info",
warn: "warn"
};
miniToastr.init({ types: toastTypes });
function toast({ type, message, title, timeout, cb }) {
return miniToastr[type](message, title, timeout, cb);
}
const options = {
success: toast,
error: toast,
info: toast,
warn: toast
};
// VueNotifications.setPluginOptions(options)
Vue.use(VueNotifications, options);
单文件引入
notifications: {
showSuccessMsg: {
type: "success",
message: "success!"
},
showErrorMsg: {
type: "error",
message: "error"
}
},
methods: {
onSubmit() {
if (Object.values(this.goodsData).indexOf("") !== -1) {
this.showErrorMsg({ message: "有必填项为空" });
return;
}
if (this.goodsData.files.length === 0) {
this.showErrorMsg({ message: "请至少上传一张图片" });
return;
}
// .......
}
}
可以看到每个页面引入还是挺麻烦的。
挂载到全局
定义:
const vm = new Vue({
el: "#app",
router,
template: "<App/>",
components: {
App
},
notifications: {
showSuccessMsg: {
type: "success",
message: "success!"
},
showErrorMsg: {
type: "error",
message: "error"
},
showInfoMsg: {
type: "info",
message: "info"
}
}
});
// 将 VueNotifications 挂载给全局, vm 实例上有消息提示方法
Vue.prototype.$notice = vm
使用:
methods: {
getMenus() {
this.$notice.showInfoMsg({ message: "菜单获取成功,$notice test" });
}
}
这两天终于解决了这个问题,记录一下。可能有更简便的用法,有时间再研究下文档。哈哈哈