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

2020-02-26  本文已影响0人  易冷zzz

首先,在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>
上一篇 下一篇

猜你喜欢

热点阅读