慕妹3146593
2022-09-02 16:59:22
我有一個特殊的場景,我想從“this”訪問數據,同時查看一個數組,該數組也在我的Vue組件上定義。例: data () { return { question: [], inputList: [], form: {} } }, methods: { onSubmit: function () { let predictionParams = {} this.inputList.forEach(function (element) { predictionParams[element.detail] = this.form[element.detail] }) }錯誤:this.form is not defined in the context of the forEach loop問題:JS處理此類案件的慣用方式是什么?我經常遇到這種情況,我總是覺得我想出了粗略的解決方案,或者至少可以做一些更容易的事情。對此的任何幫助都會很棒。
3 回答

暮色呼如
TA貢獻1853條經驗 獲得超9個贊
許多內置組件(包括 forEach)都包含一個可選的“this”活頁夾:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
利用這一點來發揮你的優勢:
this.inputList.forEach(function (element) { predictionParams[element.detail] = this.form[element.detail] },this)
自 ie9 起受支持

炎炎設計
TA貢獻1808條經驗 獲得超4個贊
arrow 函數語法避免了重新綁定此
this.inputList.forEach(element => { predictionParams[element.detail] = this.form[element.detail] })

繁星點點滴滴
TA貢獻1803條經驗 獲得超3個贊
您可以使用箭頭函數 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions 它將它綁定到函數中
data () {
return {
question: [],
inputList: [],
form: {}
}
},
methods: {
onSubmit: () => {
let predictionParams = {}
this.inputList.forEach((element) => {
predictionParams[element.detail] = this.form[element.detail]
})
}
添加回答
舉報
0/150
提交
取消