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

首先,在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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容