關(guān)于vue data中的this指向問(wèn)題
vue data的this指向
在data里定義Object類型的變量時(shí),會(huì)發(fā)現(xiàn)Object中訪問(wèn)不到vue的this屬性。
例如:
export default {
? data(){
? ? return {
? ? ? a: "123",
? ? ? b: {
? ? ? ? c: this.a
? ? ? }
? ? };
? },
? created() {
? ? console.log("b: ", this.b.c); // undefined
? }
}想在b中訪問(wèn)this.a的數(shù)據(jù),直接訪問(wèn)會(huì)返回undefined,因?yàn)檫@時(shí)c中的this指向的是b。
這種情況可以用到Object的get屬性進(jìn)行屬性定義。
例如:
export default {
? data(){
? ? return {
? ? ? a: "123",
? ? ? b: {
? ? ? ? _target: () => this,
? ? ? ? get target() {
? ? ? ? ? return this._target();
? ? ? ? },
? ? ? ? get c() {
? ? ? ? ? return this.target.a;
? ? ? ? },
? ? ? },
? ? };
? },
? created() {
? ? console.log("b: ", this.b.c); // 123
? }
}此處將this映射到了Object變量?jī)?nèi)部,然后通過(guò)get的形式定義屬性并獲取。
當(dāng)get定義的屬性所依賴的屬性的值發(fā)生改變時(shí),get定義的屬性的值也將發(fā)生改變。
例如:
export default {
? data(){
? ? return {
? ? ? a: "123",
? ? ? b: {
? ? ? ? _target: () => this,
? ? ? ? get target() {
? ? ? ? ? return this._target();
? ? ? ? },
? ? ? ? get c() {
? ? ? ? ? return this.target.a;
? ? ? ? },
? ? ? ? d: 123,
? ? ? ? get e() {
? ? ? ? ? return `依賴于d的值, 會(huì)同步發(fā)生改變, d的值為: ${this.d}`;
? ? ? ? }
? ? ? },
? ? };
? },
? created() {
? ? console.log("b: ", this.b.c); // 123
? ? console.log("e: ", this.b.e); // e: ?依賴于d的值, 會(huì)同步發(fā)生改變, d的值為: 123 c: 123
? ? setTimeout(() => {
? ? ? this.b.d = 456;
? ? ? console.log("e: ", this.b.e); // e: ?依賴于d的值, 會(huì)同步發(fā)生改變, d的值為: 456 c: 123
? ? }, 1000);
? ? setTimeout(() => {
? ? ? this.a = "456";
? ? ? console.log("e: ", this.b.e); // e: ?依賴于d的值, 會(huì)同步發(fā)生改變, d的值為: 456 c: 456
? ? }, 2000);
? }
}當(dāng)前方法更像是一種深度計(jì)算屬性(computed),會(huì)隨著所依賴的項(xiàng)發(fā)生改變而改變。
vue關(guān)于this指向的重要原則
在學(xué)習(xí)js的時(shí)候,偶爾會(huì)涉及到this的指向問(wèn)題。大部分情況下,在一個(gè)函數(shù)中,誰(shuí)調(diào)用這個(gè)函數(shù),this就指向誰(shuí)。
在Vue中,this的指向卻顯得尤為重要。本節(jié)博客將為大家解釋Vue中this的指向問(wèn)題,同時(shí)告訴讀者,為什么this的指向在Vue中非常重要,以及我們?cè)谄綍r(shí)寫Vue代碼時(shí)需要注意的相關(guān)內(nèi)容。
vue底層的相關(guān)原理
1.1 MVVM模型的復(fù)習(xí)
Vue的設(shè)計(jì)收到了MVVM模型的影響,在看this指向問(wèn)題前,我想帶讀者們復(fù)習(xí)一下MVVM模型的相關(guān)知識(shí)。
M:Model模型,對(duì)應(yīng)的是data中的數(shù)據(jù);V:View視圖,對(duì)應(yīng)的是模板,也就是頁(yè)面結(jié)構(gòu);VM:視圖模型,對(duì)應(yīng)的是Vue實(shí)例對(duì)象。
這里用一個(gè)html文件給大家劃分一下具體結(jié)構(gòu):

1.2 通過(guò)差值語(yǔ)法看vm的屬性
所有vm中的屬性,利用差值語(yǔ)法都可以看到。
為了測(cè)試,我們先看看vm是什么。此處,我們先打印一下this,可以看到此時(shí)的this是Vue。
準(zhǔn)確來(lái)說(shuō)使我們創(chuàng)建的Vue實(shí)例。這里面的所有屬性都可以通過(guò)插值語(yǔ)法看到。

為了驗(yàn)證上面說(shuō)的話,現(xiàn)在我利用差值語(yǔ)法隨意看Vue實(shí)例對(duì)象中的一些東西:


1.3 為什么差值語(yǔ)法可以看到vm的內(nèi)部屬性
==因?yàn)樵赩ue中,this指向的是vm實(shí)例對(duì)象Vue。==所以可以利用this看到vm的所有屬性。希望讀者朋友們可以牢記這一點(diǎn)。
記住這一點(diǎn)在時(shí)時(shí)刻刻的應(yīng)用中:我們不要輕易的改變this的指向,如若改變,this不再是vm,頁(yè)面上的元素將無(wú)法正常被渲染。
這里給大家看一個(gè)例子:
這段代碼的需求是,在 頁(yè)面中寫出姓和名,讓Vue幫我們合成姓名。并且在我們修改姓或者名后停頓1s后再幫我們合成。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../vue.js"></script>
</head>
<body>
<div id="root">
姓:<input type="text" v-model="firstName"><br>
名:<input type="text" v-model="lastName"><br>
全名:<span>{{ fullName }}</span>
</div>
<script>
new Vue({
el: '#root',
data: {
firstName: '張',
lastName: '三',
fullName: ''
},
watch: {
firstName(newValue, oldValue) {
setTimeout(() => {
this.fullName = newValue + this.lastName
console.log(this)
}, 1000)
},
lastName(newValue, oldValue) {
setTimeout(() => {
this.fullName = this.firstName + newValue
console.log(this)
}, 1000)
}
}
})
</script>
</body>
</html>上述代碼是沒有什么問(wèn)題的。并且在定時(shí)器中,使用箭頭函數(shù),打印出來(lái)的this都是vue實(shí)例

原因:箭頭函數(shù)中的this指向它的外層調(diào)用者。
現(xiàn)在看一個(gè)反例:我們把箭頭函數(shù)改成普通函數(shù),則會(huì)出現(xiàn)問(wèn)題:
<body>
<div id="root">
姓:<input type="text" v-model="firstName"><br>
名:<input type="text" v-model="lastName"><br>
全名:<span>{{ fullName }}</span>
</div>
<script>
new Vue({
el: '#root',
data: {
firstName: '張',
lastName: '三',
fullName: ''
},
watch: {
firstName(newValue, oldValue) {
setTimeout(() => {
this.fullName = newValue + this.lastName
console.log(this)
}, 1000)
},
// lastName(newValue, oldValue) {
// setTimeout(() => {
// this.fullName = this.firstName + newValue
// console.log(this)
// }, 1000)
// }
// 這是一個(gè)錯(cuò)誤寫法,因?yàn)樗淖兞藅his的指向。它的this是window。那么就沒辦法讀到vue中的數(shù)據(jù)了
lastName(newValue, oldValue) {
setTimeout(function() {
this.fullName = this.firstName + newValue
console.log(this)
}, 1000)
}
}
})
</script>沒辦法正常運(yùn)行并且,this打印出來(lái)的是window:


==原因:普通函數(shù)中的this指向它的直接調(diào)用者。
==由于定時(shí)器的this指向的是window。此時(shí)此刻,改變了this的指向,所以會(huì)報(bào)錯(cuò)。
心得
1.所被Vue管理的函數(shù),最好寫成普通函數(shù)。這樣的this指向?qū)嵗龑?duì)象;
2.所有不被Vue所管理的函數(shù)(定時(shí)器,ajax,回調(diào))最好寫成箭頭函數(shù),這樣this依舊指向Vue或者組件的實(shí)例對(duì)象。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue中的數(shù)據(jù)驅(qū)動(dòng)解釋
這篇文章主要為大家介紹了Vue中的數(shù)據(jù)驅(qū)動(dòng)解釋,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
使用vue-router切換頁(yè)面時(shí)實(shí)現(xiàn)設(shè)置過(guò)渡動(dòng)畫
今天小編就為大家分享一篇使用vue-router切換頁(yè)面時(shí)實(shí)現(xiàn)設(shè)置過(guò)渡動(dòng)畫。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-10-10
element-plus日歷(Calendar)動(dòng)態(tài)渲染以及避坑指南
這篇文章主要給大家介紹了關(guān)于element-plus日歷(Calendar)動(dòng)態(tài)渲染以及避坑指南的相關(guān)資料,這是最近幫一個(gè)后端朋友處理一個(gè)前端問(wèn)題,elementUI中calendar日歷組件內(nèi)容進(jìn)行自定義顯示,實(shí)現(xiàn)類似通知事項(xiàng)的日歷效果,需要的朋友可以參考下2023-08-08
Vue基礎(chǔ)之MVVM,模板語(yǔ)法和數(shù)據(jù)綁定
這篇文章主要為大家介紹了Vue之MVVM,模板語(yǔ)法和數(shù)據(jù)綁定,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2021-12-12
select的change方法傳遞多個(gè)參數(shù)的方法詳解
element-ui中的select,checkbox等組件的change方法的回調(diào)函數(shù)只有當(dāng)前選擇的val,如果想再傳入自定義參數(shù)怎么辦,本文給大家分享select的change方法如何傳遞多個(gè)參數(shù),感興趣的朋友一起看看吧2024-02-02

