this.$notify is not a function,vue使用element-ui的Notification组件时报错this.$notify is not a function

    科技2022-09-07  119

    项目场景:

    今天在写项目的时候想要寻找一个简洁好看的提示框,于是去Element-ui发现Notification 还不错,但是考虑到只使用一个Notification组件全部引入element会使项目体积变大,于是使用了局部引入的方式,但是出现了报错:this.$notify is not a function


    问题描述:

    这是我在element.js中所写的代码

    import Vue from 'vue' import { Notification, } from 'element-ui' //应用插件 Vue.use(Notification)

    这是在vue实例中使用Notification的代码

    $.post(url,this.form,(result) => { this.$notify({ title: '成功', message: result.message, type: 'success' }); this.closeDialog(); this.reloadData(); })

    然后在浏览器的控制台发现了如下错误:

    原因分析:

    去官网看了一下发现,我们在使用element-ui组件库里组件的时候,有时候是当作html标签去使用,比如<el-button></el-button>,而有时候是使用它的方法,比如这个消息提示框,在使用方法的时候如果是局部引用要将这个方法放到Vue的原型上,这样它的实例在调用这个方法的时候就不会报错了。


    解决方案:

    在element.js中添加如下代码

    Vue.prototype.$notify = Notification;

    添加后如下:

    import Vue from 'vue' import { Notification, } from 'element-ui' //应用插件 Vue.prototype.$notify = Notification;

    这样消息提示框就可以正常使用了 官方文档对引入组件的说明:

    最后附上官方文档:https://element.eleme.cn/#/zh-CN/component/quickstart

    Processed: 0.013, SQL: 9