我目前正在将 Paypal 服务集成到我的 Vue 项目中。我引用了官方文档并复制了代码https://developer.paypal.com/docs/checkout/integrate/#6-verify-the-transaction .我能够呈现 Paypal 按钮,完成交易并接收订单 ID。但是,由于以下错误,我无法将 orderID 发送到我的服务器:this.$store 未定义。 请注意,我能够在我的其他组件中引用this.$store。下面是我的以下代码:
更新:我尝试在 onApprove 方法中使用 console.log(this),它返回未定义。是这个问题吗?
更新 我已将 OnApprove 方法和 capture() 方法转换为箭头函数并收到不同的错误消息 this.$store.dispatch(...).then(...) .err 不是函数
更新 我通过将 .err() 更改为 .catch() 设法修复了上述错误。
更新 我遇到了另一个问题,有时我点击 Paypal 按钮,外部 Paypal 窗口会立即自行关闭。我必须点击按钮几次,以防止这种奇怪的行为。我去了控制台日志,发现了这条消息,如下面的截图所示。
<template>
<div>
<div id="paypal-button-container"></div>
</div>
</template>
<script>
import { PRODUCT_PAYPAL } from "@/store/actions/products";
export default {
mounted() {
paypal
.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [
{
amount: {
value: "0.01"
}
}
]
});
},
onApprove: (data, actions) => {
return actions.order.capture().then(details => {
alert("Transaction completed by " + details.payer.name.given_name);
console.log("orderID is ");
console.log(data.orderID);
// Call your server to save the transaction
return this.$store
.dispatch(PRODUCT_PAYPAL, data.orderID)
.then(() => {
alert("success");
})
.catch(() => {
alert("error");
});
});
}
})
.render("#paypal-button-container");
}
};
</script>
<style>
</style>
如下图所示,我能够收到orderID,代表交易成功。但是,this.$store 是未定义的。因此,我无法将订单 ID 发送到我的服务器
最佳答案
在回调函数上使用箭头函数,以访问this。
onApprove: (data, actions) => ...
return actions.order.capture().then((details) => ...
关于javascript - vuex this.$store undefined in "mounted"生命周期钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56131026/