vue3+elementPlus+unplugin-vue-components按需加载$message不生效问题解决方案
前提
element-plus以按需加载方式引入
https://element-plus.gitee.io/zh-CN/guide/quickstart.html#%E6%8C%89%E9%9C%80%E5%AF%BC%E5%85%A5
问题现象
在使用elementPlus按需引入时,使用options api,全局$meeage,notify,$loading
使用时会报未定义
问题原因
如果是全量引入element-plus 则不存在该问题。
按需引入时element-plus未给全局vue实例app.config.globalProperties绑定$meeage,notify,$loading
等全局方法,导致报错,需要手工绑定。
问题解决
采用插件方式安装全局方法
components/elementPlus目录新建插件文件
elementPlusMessage.js,elementPlusLoading.js,elementPlusNotify.js
elementPlusMessage.js
import 'element-plus/es/components/message/style/css'
import {ElMessage} from "element-plus"
/**
* 安装 按需引入情况下支持 $message方法
*/
export const ElementPlusMessage = {
install: (Vue) => {
let elMessage = (op) => {
return ElMessage(op)
}
elMessage.success = (op) => {
return ElMessage.success(op)
}
elMessage.warning = (op) => {
return ElMessage.warning(op)
}
elMessage.error = (op) => {
return ElMessage.error(op)
}
elMessage.info = (op) => {
return ElMessage.info(op)
}
Vue.config.globalProperties.$message = elMessage
}
}
export default ElementPlusMessage
elementPlusLoading.js
import 'element-plus/es/components/loading/style/css'
import {ElLoading} from "element-plus"
/**
* 安装 按需引入情况下支持 $loading方法
*/
export const ElementPlusLoading = {
install: (Vue) => {
Vue.config.globalProperties.$loading = (op) => {
return ElLoading.service(op)
}
}
}
export default ElementPlusLoading
elementPlusNotify.js
import 'element-plus/es/components/notification/style/css'
import {ElNotification} from "element-plus"
/**
* 安装 按需引入情况下支持 $notify 方法
*/
export const ElementPlusNotify = {
install: (Vue) => {
let notification = (op) => {
return ElNotification(op);
}
notification.success = (op) => {
return ElNotification.success(op)
}
notification.warning = (op) => {
return ElNotification.warning(op)
}
notification.error = (op) => {
return ElNotification.error(op)
}
notification.info = (op) => {
return ElNotification.info(op)
}
Vue.config.globalProperties.$notify = notification
}
}
export default ElementPlusNotify
main.js修改安装插件
import ElementPlusLoading from "@components/elementPlus/elementPlusLoading";
import ElementPlusMessage from "@components/elementPlus/elementPlusMessage";
import ElementPlusNotify from "@components/elementPlus/elementPlusNotify";
const app = createApp(App)
.use(ElementPlusLoading)
.use(ElementPlusMessage)
.use(ElementPlusNotify)
.use(router).mount('#app')
至此,可以正常使用$meeage,notify,$loading
等全局方法