Vue + Element 中 this.$message 失效问题解决方法,undefined 是什么原因?
微wx笑
 2022-01-25【前端开发】
 3
 0关键字:
Vue  Element  
this.$message undefined 是什么原因?应该怎么办?其实是this的作用域的问题。使用全局变量Vue.prototype来调$message()就可以了,这在官方文档有说明;或者重新定义this也是可以的。
Vue的Element确实给开发者提供了很大的便捷,比如消息提示中的:this.$message 函数就非常好用。但是在某些情况下是失效的,比如如下代码所示:
onSubmit: function () {
    if (this.formInline.title === '') {
        // 这里可以成功使用$message函数
        this.$message({
            message: '失败!',
            type: 'warning'
        });
    } else {
        $.post('upload',
            {
                title: this.formInline.title,
            },
            function (res) {
                // 这里使用$message函数则是失效的
                this.$message({
                    message: '成功!',
                    type: 'success'
                });
            });
    }
},可以看到后台返回的数据使用this.$message就会失效,因为 this 指的不再是Vue了,所以... ...
Vue.prototype.$message({
    message: '成功!',
    type: 'success'
});onSubmit: function () {
    var vm = this;
    if (this.formInline.title === '') {
        // 这里可以成功使用$message函数
        this.$message({
            message: '失败!',
            type: 'warning'
        });
    } else {
        $.post('upload',
            {
                title: this.formInline.title,
            },
            function (res) {
                // 这里就可以用了
                vm.$message({
                    message: '成功!',
                    type: 'success'
                });
            });
    }
},以上部分转自:https://blog.csdn.net/hongyuancao/article/details/88078575
后来发现,官方文档有说明的:
全局方法
Element 为 Vue.prototype 添加了全局方法 $message。因此在 vue instance 中可以采用本页面中的方式调用 Message。
全局方法
如果你完整引入了 Element,它会为 Vue.prototype 添加如下全局方法:$msgbox, $alert, $confirm 和 $prompt。因此在 Vue instance 中可以采用本页面中的方式调用 MessageBox。调用参数为:
$msgbox(options)$alert(message, title, options)或$alert(message, options)$confirm(message, title, options)或$confirm(message, options)$prompt(message, title, options)或$prompt(message, options)
全局方法
Element 为 Vue.prototype 添加了全局方法 $notify。因此在 vue instance 中可以采用本页面中的方式调用 Notification。
本文由 微wx笑 创作,采用 署名-非商业性使用-相同方式共享 4.0  许可协议,转载请附上原文出处链接及本声明。
原文链接:https://www.ivu4e.cn/blog/front/2022-01-25/972.html



