SoFunction
Updated on 2025-03-02

Implementation in vue3 uses element-plus to call message

vue3 calls message using element-plus

Environment: vue3+typescript+element-plus

1. After the global introduction of element

element has added the global method $message

So it can be used directly in the options API

  mounted(){
    (this as any).$("this.$message");
  }

2. In the Composition API, the setup method passes in two variables.

Props and context, context replaces this as context, but only emit, attrs, and slots in the context, and if this is directly used in the setup, problems will arise: Description of the official website:

Inside setup(), this will not be a reference to the active instance, because setup() is called before parsing other component options, so this inside setup() behaves completely differently from this in other options. This can cause confusion when used with other option APIs setup() .

So you can use the getCurrentInstance method to get the instance. This method can be used directly after global introduction of element-plus

//
import { getCurrentInstance, defineComponent,onMounted } from 'vue';
export default  = defineComponent{
setup(omprops,content){
    onMounted(()=>{
      getCurrentInstance()?..$("clever");
    })
}

3. Another way is to use provide/inject

//
import { createApp } from 'vue'
import App from './'
import element from 'element-plus'
import 'element-plus/lib/theme-chalk/'
import {ElMessage} from 'element-plus'
const app = createApp(App)
(element)
//If there is no global reference element, you need to write the following sentence//.$message = ElMessage;
('$message', ElMessage)
('#app')
//
import { inject, defineComponent,onMounted } from 'vue';
export default  = defineComponent{
setup(omprops,content){
    onMounted(()=>{
      (inject('$message') as any).success("inject");
    })
}

4. The easiest way to write in the Composition API is to introduce it on demand

//
import { inject, defineComponent,onMounted } from 'vue';
import { ElMessage } from 'element-plus'
export default  = defineComponent{
setup(omprops,content){
    onMounted(()=>{
      ('Introduction on demand');
    })
}

vue uses Element's message component

Use in vue files

this.$message({
  message: "Prompt message",
  type: "success"
})

Use in js file

({
  message: 'Prompt message',
  type: 'warning'
});

The above is personal experience. I hope you can give you a reference and I hope you can support me more.