vue箭头函数与普通函数

Posted Onemorelight95

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue箭头函数与普通函数相关的知识,希望对你有一定的参考价值。

vue普通函数与箭头函数


文章目录


其实两者最大的不同就是它们的this指向。

普通函数

普通函数中的this代表它的直接调用者, 例如 obj.cal() ,那么cal()方法中的this就是obj,而如果没找到直接调用者,则this指的是 window。

箭头函数

箭头函数不绑定this,它会捕获所在的上下文的this值,作为自己的this值。

两者对比示例

普通函数:

var name = '张三'var person = 
        name:'小马哥',           
        age:18,
        fav:function()
            console.log(this)
            console.log(this.name)
        
    
person.fav();
// name: "小马哥"

此时this指向的是使用它的对象,也就是person对象。

箭头函数:

var person2 = 
    name:'小马哥',
    age:18,
    fav: ()=>
         // 当前this指向了定义时所在的对象(window)
         console.log(this);
      
    
person2.fav();
// Window

使用箭头函数,它表示定义时所在的对象window。

什么时候使用箭头函数

当把一个函数的结果(返回值)作为另一个函数的参数的时候,就可以使用箭头函数了。比如使用axios回显数据的时候:

axios.get('static/data.json').then(function(res)
	console.log(this)    //undefined
	this.user = res.data.user
)

以上的代码会报错,因为在外部,this指向的是当前创建的vue实例,而在这些函数内部,使用例如axios与后台交互后回调函数的内部的this并非指向当前的vue实例。如果想拿到后台回传的数据更新data里的数据,不能在回调函数中直接使用this。这个时候我们有两种方式:定义一个变量来储存this或者使用箭头函数。

第一种方法:

var _this = this
axios.get('static/data.json').then(function(res)
	console.log(this)    //undefined
	console.log(_this)   //VueComponent _uid: 1, _isVue: true, $options: …, _renderProxy: Proxy, _self: VueComponent, …
	_this.user = res.data.user
)

第二种方法:

axios.get('static/data.json').then((res) => 
	console.log(this)      //VueComponent _uid: 1, _isVue: true, $options: …, _renderProxy: Proxy, _self: VueComponent, …
	this.user = res.data.user
)

以上是关于vue箭头函数与普通函数的主要内容,如果未能解决你的问题,请参考以下文章

Python 操作Redis

python爬虫入门----- 阿里巴巴供应商爬虫

Python词典设置默认值小技巧

《python学习手册(第4版)》pdf

Django settings.py 的media路径设置

Python中的赋值,浅拷贝和深拷贝的区别