Vue中PayPal按钮回调内this指向异常无法访问props与data的解决咨询
问题原因
- 你遇到的this指向异常,不是箭头函数的规则无效,而是定义createOrder箭头函数时的外层作用域的this已经不是Vue实例,箭头函数的this会继承外层作用域的this,所以自然拿不到props和data里的变量。
- 你的代码还存在一个语法错误:
quantity: this.quantity.toString这里没有调用toString方法,少了括号,会导致PayPal侧参数解析错误。
解决方案
最稳妥的方式是提前把Vue实例存到局部变量,完全避开this指向问题,修改后的代码如下:
// 在PayPal按钮初始化的外层先保存Vue实例 const vm = this await paypal.Buttons({ style: { layout: 'vertical', color: 'black', shape: 'pill', }, createOrder: (data, actions) => { return actions.order.create({ purchase_units: [{ amount: { currency_code: "USD", value: ((vm.price + vm.shipping) * vm.quantity).toString(), breakdown: { item_total: { /* Required when including the `items` array */ currency_code: "USD", value: vm.price.toString() }, shipping: { currency_code: "USD", value: vm.shipping.toString() } } }, items: [ { name: "First Product Name", /* Shows within upper-right dropdown during payment approval */ description: "Optional descriptive text..", /* Item details will also be in the completed paypal.com transaction view */ unit_amount: { currency_code: "USD", value: vm.price.toString() }, // 修复toString未调用的问题 quantity: vm.quantity.toString() }, ] }] }); }, }).render('#paypal-button-container')
关于this指向的补充说明
箭头函数本身没有独立的this,它的this完全等于定义时所在的外层作用域的this,不会被调用方修改。如果你需要用箭头函数绑定Vue实例的this,需要保证包裹这段代码的外层函数(比如mounted钩子、自定义methods)本身的this是Vue实例:
- 如果外层是Vue的生命周期钩子、methods里的普通函数,this默认就是Vue实例,里面的箭头函数就能继承到正确的this
- 如果外层还有其他普通函数回调(比如定时器、第三方库的普通函数回调),就会导致外层this被修改,箭头函数继承到的this也会出错
内容的提问来源于stack exchange,提问作者Nash Anderson
相关产品推荐
相关产品推荐

