一、this的基本使用
this是Vue实例中非常重要的一个属性,它代表当前组件实例,常用于引用组件中的数据及方法。
如下面的代码,在Vue中使用this.message来引用message数据:
{
  data() {
    return {
      message: "Hello, Vue3 this!"
    }
  },
  methods: {
    showMessage() {
      alert(this.message);
    }
  }
}
在以上代码中,this代表当前的组件实例,可以直接通过this.message引用组件中的数据。同理,在methods中的showMessage方法中,使用this.message也可以引用message数据。
二、箭头函数中的this
在Vue3中,箭头函数的this指向包含它的作用域,而不是运行时所在的作用域。因此,在箭头函数内部使用this会指向外层作用域,而非Vue实例本身。
如下面的代码,在Vue中使用箭头函数调用showMessage方法,this将指向window对象:
{
  data() {
    return {
      message: "Hello, Vue3 this!"
    }
  },
  methods: {
    showMessage: () => {
      alert(this.message);
    }
  }
}
在以上代码中,使用箭头函数定义了showMessage方法,而在这个方法中使用this.message时,this指向的是window对象,所以会弹出undefined提示。
三、computed中的this
在computed属性中,this同样表示当前组件实例。
如下面的代码,在Vue中使用computed属性定义一个fullName属性,使用this.firstName和this.lastName来引用组件中的数据:
{
  data() {
    return {
      firstName: "Tom",
      lastName: "Smith"
    }
  },
  computed: {
    fullName() {
      return this.firstName + " " + this.lastName;
    }
  }
}
在以上代码中,this.firstName和this.lastName都是引用了组件中的数据,而且在computed属性中使用this来引用组件数据更方便。
四、watch中的this
在watch属性中,this同样表示当前组件实例。
如下面的代码,在Vue中使用watch属性监听message的变化,当message改变时,使用this.showMessage方法进行提示:
{
  data() {
    return {
      message: "Hello, Vue3 this!"
    }
  },
  methods: {
    showMessage() {
      alert(this.message);
    }
  },
  watch: {
    message() {
      this.showMessage();
    }
  }
}
在以上代码中,当message数据改变时,watch会监听到并执行showMessage方法,因为使用了this来引用组件中的方法。
五、组件方法中的this
在Vue3中,组件中的方法this同样表示当前组件实例。
如下面的代码,在Vue中定义一个Child组件,使用this来引用组件中的数据和方法:
{
  // Child组件
  components: {
    Child: {
      template: '<div><p>{{ message }}</p><button @click="showMessage">Click me!</button></div>',
      data() {
        return {
          message: "Hello, Vue3 this!"
        }
      },
      methods: {
        showMessage() {
          alert(this.message);
        }
      }
    }
  },
  // 父组件
  template: ''
}
在以上代码中,使用this来引用Child组件中的数据和方法,实现了组件之间的通讯。
原创文章,作者:HZILU,如若转载,请注明出处:https://www.506064.com/n/373174.html
 
 微信扫一扫
微信扫一扫  支付宝扫一扫
支付宝扫一扫 