2👍
Many built-ins, including forEach include an optional ‘this’ binder:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
use that to your advantage:
this.inputList.forEach(function (element) {
predictionParams[element.detail] = this.form[element.detail]
},this)
supported since ie9
1👍
arrow function syntax avoids rebinding this
this.inputList.forEach(element => {
predictionParams[element.detail] = this.form[element.detail]
})
1👍
You can use Arrow function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
It will binding this into the function
data () {
return {
question: [],
inputList: [],
form: {}
}
},
methods: {
onSubmit: () => {
let predictionParams = {}
this.inputList.forEach((element) => {
predictionParams[element.detail] = this.form[element.detail]
})
}
Source:stackexchange.com