vue中this的指向

vue中this的指向

1.在Vue所有的生命周期钩子方法

  比如在mounted里使用this,this指向调用它的Vue实例,如下列子:
在这里插入图片描述

2.vue组件生命周期钩子方法里面还有方法使用this

  在函数内部使用this时,this会指向window,而非vue实例。所以除了vue组件自身方法外,在别的地方调用this时, 首先需要在最外部,设置一个变量,将其绑定上vue实例。
在这里插入图片描述

3.vue普通方法中使用this

  this指向调用它的Vue实例
在这里插入图片描述

4.vue箭头方法中使用this

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

在这里插入图片描述

  完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
      <button v-on:click="show" >按钮1</button>
      <button v-on:click="show2" >按钮2</button>
      <p>{{date}}</p>
    </div>
    <script src="vue.js"></script>
    <script>
        var name = 'hello';
        var app = new Vue({
            el:'#app',
            data:{name:"你好",date:new Date()},
            methods:{
                show:function()
                {
                    console.log('普通方法.............................');
                    console.log(this.name);
                    console.log(this);
                },
                // 箭头方法
                show2 :() =>
                {
                    console.log('箭头方法.............................');
                    console.log(this.name);
                    console.log(this);
                }
            },
            mounted:function()
            {
                console.log('Vue所有的生命周期钩子方法.............................');
                console.log(this);
                console.log(this.name);
                _this = this;
                    this.timer = setInterval(function(){
                   
                        _this.date = new Date();
                        console.log('vue组件生命周期钩子方法里面还有方法使用this.............................');
                        console.log(_this.name);
                        console.log(_this);
                        console.log(this.name);
                        console.log(this);
                    },10000);



            }
        
        })
    </script>
</body>
</html>
  • 8
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值