Vue + Element 中 this.$message 失效问题解决方法

⭐️个人博客:caohongyuan,更多分享,欢迎浏览!⭐️

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

使用全局变量Vue.prototype来调$message()就可以了。

或者重新定义this也是可以的。如下:

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

欢迎指导!

千而の大狮子~

  • 19
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值