一、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/zh-hant/n/373174.html