当前位置:首页 > 前端

js关于this的小技巧

Z先生5年前 (2020-11-19)前端898

这段时间,vue写的多了,习惯了es6的方式写函数,但是这种写法很容易导致this失效,比如刚刚发布的vue深度监听的问题,用了es6的写法,this就没法用,换回传统写法就可以了。

// es6写法,这样写this没法用,this成windows对象了
watch: {
data: {
handler: (newVal, oldVal) => {
console.log('data', newVal);
},
deep: true,
immediate: true
}
},

传统写法

// 传统写法
watch: {
data: {
handler: function(newVal, oldVal){
console.log('data', newVal);
},
deep: true,
immediate: true
}
},

经查资料获得因为这个时候watch使用的是=>,是箭头函数,那么这时候的this,其实是window对象,而不是当前vue 对象。

分享给朋友:

相关文章

antd vue版一些小细节

复选框选择默认选择,但是不要使用属性手上的checked,否则渲染后无法动态修改,有defaultChecked方法,但是测试无效,所以使用valuePropName:˂a-checkbox styl…

问题: - did you register the component correctly......

问题: - did you register the component correctly......

问题:无法使用tree组件提示 Unknown custom element:<a-tree> - did you register the component correctly? Fo…

elemeui表格中点击修改最优雅的方式

需求表格中,某一列需要点击修改。并且能拦截回车事件。 解决方案vue代码 {{ row.order }} JS methods 方法```…

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。