一、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: '<child />'
}
在以上代码中,使用this
来引用Child组件中的数据和方法,实现了组件之间的通讯。