最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
vue3中实现使用element-plus调用message代码示例
时间:2022-09-07 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下vue3中实现使用element-plus调用message代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
环境:vue3+typescript+element-plus
1. 全局引入element之后
element已经在 app.config.globalProperties 添加了全局方法 $message
所以在options API中可以直接使用
mounted(){ (this as any).$message.success("this.$message"); }
2. 在Composition API中setup方法传入了两个变量
props和context,context作为上下文取代this,但是context中只有emit,attrs,和slots,而直接在setup中使this,会出现问题:官方网站的说明:
在 setup() 内部,this 不会是该活跃实例的引用,因为 setup() 是在解析其它组件选项之前被调用的,所以 setup() 内部的 this 的行为与其它选项中的 this 完全不同。这在和其它选项式 API 一起使用 setup() 时可能会导致混淆。
所以可以使用getCurrentInstance方法获取实例。此方法在全局引入element-plus之后就可直接使用
//helloworld.vue import { getCurrentInstance, defineComponent,onMounted } from 'vue'; export default = defineComponent{ setup(omprops,content){ onMounted(()=>{ getCurrentInstance()?.appContext.config.globalProperties.$message.success("聪明"); }) }
3. 还有一种方法是使用 provide/inject
//main.ts import { createApp } from 'vue' import App from './App.vue' import element from 'element-plus' import 'element-plus/lib/theme-chalk/index.css' import {ElMessage} from 'element-plus' const app = createApp(App) app.use(element) //如果没有全局引用element,还需写下面一句 //app.config.globalProperties.$message = ElMessage; app.provide('$message', ElMessage) app.mount('#app')
//helloworld.vue import { inject, defineComponent,onMounted } from 'vue'; export default = defineComponent{ setup(omprops,content){ onMounted(()=>{ (inject('$message') as any).success("inject"); }) }
4. 在Composition api中最简单的写法就是按需引入
//helloworld.vue import { inject, defineComponent,onMounted } from 'vue'; import { ElMessage } from 'element-plus' export default = defineComponent{ setup(omprops,content){ onMounted(()=>{ ElMessage.success('按需引入'); }) }
vue使用Element的message组件
在vue文件中使用
this.$message({ message: "提示信息", type: "success" })
在js文件中使用
ElementUI.Message({ message: '提示信息', type: 'warning' });
相关文章
- SpringBoot测试配置属性与web启动环境解析 10-24
- SpringBoot常用计量与bean属性校验和进制数据转换规则解析 10-24
- 工厂方法在Spring框架中的运用介绍 10-24
- SpringBoot热部署设置详解 10-24
- JavaScript二叉搜索树构建操作解析 10-12
- JavaScript二叉树及各种遍历算法讲解 10-12