vue报错:Uncaught (in promise) TypeError: Cannot read property ‘$message‘ of undefined

今天项目搭建的时候遇到一个问题:

Uncaught (in promise) TypeError: Cannot read property '$message' of undefined

看到这里我知道肯定是elementui的messagebox组件出现了问题,查看elementui的官方文档,

全局方法

如果你完整引入了 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)
单独引用

如果单独引入 MessageBox:
import {
    
     MessageBox } from 'element-ui';
那么对应于上述四个全局方法的调用方法依次为:MessageBox, MessageBox.alert, MessageBox.confirm 和 MessageBox.prompt,调用参数与全局方法相同。

需求文档中的意思是,当你全局导入的时候,不需要把组件挂载到原型上,直接使用即可,如果是按需导入,则就得需要除了导入messagebox之外,还要把组件挂载到原型上。当时搭建项目的时候我是做的全局导入,于是采用了第一种方法,但是运行时报上面这个错。后面查了好多资料才知道原因。
代码是这样的:

	this.$http.post('login',this.Loginform).then((res)=>{
    
    
							console.log(this)
							console.log(res.status)
							if (res.status == 200){
    
    
								console.log("1111")
								this.$message("登录成功!")
							}
						})

其实这个报错原因是this的指向问题,之前没用箭头函数,而是用的匿名函数,当使用匿名函数的时候this的值是undefined,自然不能使用this. m e s s a g e ( ) , 而 当 使 用 匿 名 函 数 的 时 候 , t h i s 指 的 是 v u e 对 象 , 便 可 以 使 用 t h i s . message(),而当使用匿名函数的时候,this指的是vue对象,便可以使用this. message(),使thisvue便使this.message。

对于为什么是undefined,看这篇博客吧。

https://zhuanlan.zhihu.com/p/78370263

Guess you like

Origin blog.csdn.net/qq_45791799/article/details/119253768