vue中的普通函数与箭头函数以及this关键字

普通函数

普通函数指的是用function定义的函数

var hello = function () {
    console.log("Hello, Fundebug!");
}

箭头函数

箭头函数指的是用=>定义的函数

var hello = () => {
    console.log("Hello, Fundebug!");
}

箭头函数没有自己的this值,箭头函数中所使用的this来自于函数作用域链。

this

this就是代码执行时当前的context object。

The JavaScript context object in which the current code is executing.

Global context

代码没有在任何函数中执行,而是在全局作用域中执行时,this的值就是global对象,对于浏览器来说,this就是window。

In the global execution context (outside of any function), this refers to the global object whether in strict mode or not.

Function context

函数中的this值取决于这个函数是怎样被调用

Inside a function, the value of this depends on how the function is called.

axios中this的指向问题

在vue中使用axios做网络请求的时候,会遇到this不指向vue,而为undefined。
解决办法:使用箭头函数 "=>"
"=>" 内部的this是词法作用域,由上下文确定(也就是由外层调用者vue来确定)。

methods: {
      loginAction(formName) {
        this.$axios.post("……")
          .then(function(response){
               console.log(this); //这里 this = undefined
          })
          .catch((error)=> {
              console.log(this); //箭头函数"=>"使this指向vue
          });

        });
      }
}

相关文章

可以通过min-width属性来设置el-table-column的最小宽度。以...
yarn dev,当文件变动后,会自动重启。 yanr start不会自动重...
ref 用于创建一个对值的响应式引用。这个值可以是原始值(如...
通过修改 getWK005 函数来实现这一点。这里的 query 参数就是...
<el-form-item label="入库类型" ...
API 变动 样式类名变化: 一些组件的样式类名有所变动,可能需...