Environment: vue3 typescript element-plus
element has added the global method $message
in app.config.globalProperties, so it can be used directly in the options API
mounted(){ (this as any).$message.success("this.$message"); }
props and context. context replaces this as the context, but context only has emit, attrs, and slots. If this is used directly in setup, problems will occur: Official website Note:
Inside setup(), this will not be a reference to the active instance, because setup() is called before parsing other component options, so the behavior of this inside setup() is different from other This in options is completely different. Confusion can occur when you use it with other optional APIs in setup().
Therefore, the instance can be obtained by calling the getCurrentInstance method. This method can be used directly after introducing element-plus globally
//helloworld.vue import { getCurrentInstance, defineComponent,onMounted } from 'vue'; export default = defineComponent{ setup(omprops,content){ onMounted(()=>{ getCurrentInstance()?.appContext.config.globalProperties.$message.success("聪明"); }) }
//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"); }) }
//helloworld.vue import { inject, defineComponent,onMounted } from 'vue'; import { ElMessage } from 'element-plus' export default = defineComponent{ setup(omprops,content){ onMounted(()=>{ ElMessage.success('按需引入'); }) }
Use it in the vue file
this.$message({ message: "提示信息", type: "success" })
Use it in the js file
ElementUI.Message({ message: '提示信息', type: 'warning' });
The above is the detailed content of How to use element-plus to call message in vue3. For more information, please follow other related articles on the PHP Chinese website!