温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue3中怎么使用element-plus调用message

发布时间:2022-09-07 09:43:46 来源:亿速云 阅读:1293 作者:iii 栏目:开发技术

今天小编给大家分享一下vue3中怎么使用element-plus调用message的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

    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'
    });

    以上就是“vue3中怎么使用element-plus调用message”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI