this 使用問題
大部分開發者都會合理、巧妙的運用 this
關鍵字。
初學者容易在 this
指向上犯錯,如下面這個 Vue 組件
:
<div id="app"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
<script>
// 發送post請求
const post = (cb) => {
// 假裝發了請求并在200ms后返回了服務端響應的內容
setTimeout(function() {
cb([
{
id: 1,
name: '小紅',
},
{
id: 2,
name: '小明',
}
]);
});
};
new Vue({
el: '#app',
data: function() {
return {
list: [],
};
},
mounted: function() {
this.getList();
},
methods: {
getList: function() {
post(function(data) {
this.list = data;
console.log(this);
this.log(); // 報錯:this.log is not a function
});
},
log: function() {
console.log('輸出一下 list:', this.list);
},
},
});
</script>
這是初學 Vue
的同學經常碰到的問題,為什么這個 this.log()
會拋出異常,打印了 this.list
似乎也是正常的。
這其實是因為傳遞給 post
方法的回調函數,擁有自己的 this,有關內容可以查閱 this章節。
不光在這個場景下,其他類似的場景也要注意,在寫回調函數的時候,如果在回調函數內要用到 this
,就要特別注意一下這個 this
的指向。
可以使用 ES6 的箭頭函數
或者將需要的 this 賦值給一個變量,再通過作用域鏈的特性訪問即可:
<div id="app"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
<script>
// 發送post請求
const post = (cb) => {
// 假裝發了請求并在200ms后返回了服務端響應的內容
setTimeout(function() {
cb([
{
id: 1,
name: '小紅',
},
{
id: 2,
name: '小明',
}
]);
});
};
new Vue({
el: '#app',
data: function() {
return {
list: [],
};
},
mounted: function() {
this.getList();
},
methods: {
getList: function() {
// 傳遞箭頭函數
post((data) => {
this.list = data;
console.log(this);
this.log(); // 報錯:this.log is not a function
});
// 使用保留 this 的做法
// var _this = this;
// post(function(data) {
// _this.list = data;
// console.log(this);
// _this.log(); // 報錯:this.log is not a function
// });
},
log: function() {
console.log('輸出一下 list:', this.list);
},
},
});
</script>
這個問題通常初學者都會碰到,之后慢慢就會形成習慣,會非常自然的規避掉這個問題。