美文网首页
vue组件内箭头函数的this指向问题

vue组件内箭头函数的this指向问题

作者: 易冷zzz | 来源:发表于2020-02-26 01:14 被阅读0次

首先,在Vue所有的生命周期钩子方法(如beforeCreate,created,beforeMount,mounted,beforeUpdate, updated,beforeDestroy以及destroyed)里使用this,this指向调用它的Vue实例,即(new Vue)。

其次,箭头函数没有自己的this, 它的this是继承而来; 默认指向在定义它时所处的对象(宿主对象),而不是执行时的对象。

以下例子详细解释:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>

</head>
<body>
    <div id="app">
        
    </div>
</body>
<script src="https://unpkg.com/vue@2.5.9/dist/vue.js"></script>
<script type="text/javascript">
    let vm = new Vue({
        el:"#app",
        data(){
            return {
                dataList: [1,2,3],
            }
        },
        mounted(){
            this.group1()
            this.group2()
            this.group3()
            this.group4()
            this.group5()
            
        },
        methods:{
            group1(){
                //ES6普通函数写法,this指向Vue实例
                console.log('group1:',this)
            },
            group2:function(){
                //ES5的普通函数写法,this指向Vue实例
                console.log('group2:',this)
            },
            group3:() => {
                //ES6的箭头函数写法,箭头函数没有自己的this,它的this继承来的,指向在定义它时所处的宿主对象,在这里this指向window。
                console.log('group3:',this)
            },
            group4(){
                console.log('group4:',this)
                this.dataList.forEach(function(obj){
                    //在匿名函数中,这里的this指向window,在严格模式下,this指向undefined
                    console.log('group4-1:',this)
                })
            },
            group5:function(){
                console.log('group5:',this)
                this.dataList.forEach((obj)=>{
                    //箭头函数的this继承来的,这里的this指向跟上一级的this指向相同,即Vue实例
                    console.log('group5-1:',this)
                })
            }
        },
    })
   
</script>
</html>

相关文章

  • vue组件内箭头函数的this指向问题

    首先,在Vue所有的生命周期钩子方法(如beforeCreate,created,beforeMount,moun...

  • js prototype

    this 指向 箭头函数里的 this 指向声明函数的地方,也就是组件内,所以不用 bind(this)普通函数里...

  • vue 2 method 的this 失效

    不能用箭头函数,剪头函数的this不指向vue 实例

  • Es6知识点总结

    methods 不能使用箭头函数 为啥?在箭头函数中使用this的话指向的是组件本身 如果不使用箭头函数 this...

  • 前端小白成长04--Object.is  this

    Object.is()确定两个值是否相同 Ie不支持 this指向在箭头函数内是没有 this 指向的,箭头函数里...

  • ES6新特性(更新篇)

    首先感谢Carnia帮我指出ES6箭头函数中this指向的错误,此次主要更新箭头函数中this指向问题。 ECMA...

  • this指向全解

    结论:函数中this总是指向调用它的对象(箭头函数除外、特殊情况除外)。 对象字面量。 箭头函数内的this向上指...

  • vue入门

    (1)不要在选项属性或回调上使用箭头函数:箭头函数是和父级上下文绑在一起的(2)vue中不能在子组件的模板内直接引...

  • 箭头函数和普通函数的主要区别是什么?

    箭头函数和普通函数的主要区别: this的指向问题,箭头函数是不存在this的(也是箭头函数和普通函数最主要的区别...

  • React Native 关于箭头函数、普通函数与点击事件的调用

    箭头函数 箭头函数一个重要的好处就是对于this对象指向问题,在普通函数中this对象的指向是可变的,所以在普通函...

网友评论

      本文标题:vue组件内箭头函数的this指向问题

      本文链接:https://www.haomeiwen.com/subject/uvndchtx.html