[英]Calling a function to apply discounts before submitting the form in VUE.JS
在使用 Axios 提交表单之前,我需要对我的 campaign.items 中的每个项目应用相应的折扣。
为此,我有一个可以正常工作的 function:
applyDiscount(price) {
return price - (this.totalDiscount * price)
},
在提交之前,我将 function 调用放在我的提交 function 中:
methods: {
submit() {
this.campaign.items.forEach(function(item) {
this.applyDiscount(item.price)
}),
var data = new FormData()
我收到错误:
Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'applyDiscount')"
问题是你的匿名 function 里面的this
和外面的不this
。 通常,您可以做的是通过执行let that = this;
之前获得this
的引用。 然后在另一个 function 中使用that
:
class Demo { applyDiscount() { console.log('hi'); } example() { var that = this; [1,2].forEach(function() { that.applyDiscount(); }) } } let x = new Demo(); x.example()
或者你可以绑定这个:
class Demo { applyDiscount() { console.log('hi'); } example() { [1,2].forEach((function() { this.applyDiscount(); }).bind(this)) } } let x = new Demo(); x.example()
或者您可以使用箭头 function:
class Demo { applyDiscount() { console.log('hi'); } example() { [1,2].forEach(() => { this.applyDiscount(); }) } } let x = new Demo(); x.example()
我也会这样做,我想“全局” this
不等于组件this
。
箭头 function 应该有效,
methods: {
submit() {
this.campaign.items.forEach((item) => {
this.applyDiscount(item.price)
}),
var data = new FormData()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.