在Vue中,可以使用this關鍵字來訪問到組件中定義的變量。然而,在axios的then函數中,this關鍵字的作用域會改變,會指向axios對象本身而不是Vue組件實例。因此,不能直接訪問到Vue組件中定義的變量。
解決這個問題的一種方法是將Vue組件中定義的變量保存到一個變量中,然后在axios的then函數中使用該變量。例如:
var self = this;axios.get('/api/some-data').then(function (response) {// 使用self變量來訪問Vue組件中的變量console.log(self.myVariable);}).catch(function (error) {console.log(error);});
另外,也可以使用箭頭函數來解決this關鍵字作用域的問題,因為箭頭函數會繼承父級作用域的this值。例如:
axios.get('/api/some-data').then((response) => {// 使用this關鍵字來訪問Vue組件中的變量console.log(this.myVariable);}).catch((error) => {console.log(error);});
使用箭頭函數的好處是不需要額外保存this關鍵字的值,直接在then函數中使用this關鍵字來訪問Vue組件的變量即可。