Vue例項裡this的使用

2021-09-16 13:40:34 字數 1461 閱讀 5660

這是vue文件裡的原話:

all lifecycle hooks are called with their 'this' context pointing to the vue instance invoking it.

意思是:在vue所有的生命週期鉤子方法(如created,mounted, updated以及destroyed)裡使用this,this指向呼叫它的vue例項。

示例定義了兩個message。乙個是全域性變數,即window.message,它的值為英文「hello!」。另外乙個是vue例項的資料message,它的值為中文的「你好!」。

執行示例,在瀏覽器得到:

第乙個輸出英文"hello!」,第二個輸出中文「你好!」。這說明了showmessage1()裡的this指的是window,而showmessage2()裡的this指的是vue例項。

created

created: function()
created函式為vue例項的鉤子方法,它裡面使用的this指的是vue例項。

showmessage1()

showmessage1:function(), 10)

}

對於普通函式(包括匿名函式),this指的是直接的呼叫者,在非嚴格模式下,如果沒有直接呼叫者,this指的是window。showmessage1()裡settimeout使用了匿名函式,this指向window。

showmessage2()

showmessage2:function() , 10)

}

箭頭函式是沒有自己的this,在它內部使用的this是由它定義的宿主物件決定。showmessage2()裡定義的箭頭函式宿主物件為vue例項,所以它裡面使用的this指向vue例項。

為了避免this指向出現歧義,有兩種方法繫結this。

使用bind

showmessage1()可以改為:

showmessage1:function().bind(this), 10)

}

對settimeout()裡的匿名函式使用bind()繫結到vue例項的this。這樣在匿名函式內的this也為vue例項。

把vue例項的this賦值給另乙個變數再使用

showmessage1()也可以改為

showmessage1:function().bind(this), 10)

}

這裡把表示vue例項的this賦值給變數self。在使用到this的地方改用self引用。

Vue例項裡this的使用

這是vue文件裡的原話 all lifecycle hooks are called with their this context pointing to the vue instance invoking it.意思是 在vue所有的生命週期鉤子方法 如created,mounted,updat...

在vue專案中的js檔案裡使用vue例項

參考的 不為其他,就為了記錄一下,方便以後檢視 1 首先在http.js中 定義乙個變數context用來接收vue,再定乙個initvue方法傳入的引數是vue,並匯出這個方法。import axios from axios const time out ms 60 1000 預設請求超時時間 l...

vue例項的資料使用

一 vue例項可以使用的資料有哪些 1 例項本身有data computed props 2 例項原型上有 store router parent son refs等 二 可以使用這些資料的位置 1 template模板中的雙花括號中 vuex中狀態title data computed props...