你的问题是这条线
axios.post(this.api+"orders",this.order).then(function(response) {
示例可能会this
像您所说的那样使用,但是通过使用第二级嵌套函数表达式,您访问的动态this
与您认为的不同。
基本上,send
是 Vue 对象的方法,但由于this
不在function
表达式内部的词法范围内,仅在函数内部,所以您在传递给的回调中=>
有错误的引用。this
Promise.prototype.then
这是一个细分:
methods: {
send: function() {
// here: `this` technically refers to the `methods` object
// but Vue lifts it to the entire view object at runtime
axios.post(this.api + "orders", this.order)
.then(function(response) {
// here: `this` refers to the whatever object `the function is called on
// if it is called as a method or bound explicitly using Function.prototype.bind
// the Promise instance will not call it on anything
// nor bind it to anything so `this` will be undefined
// since you are in a module and modules are implicitly strict mode code.
this.message = "Your payment was successful";
});
}
}
试试这个
export default {
data() {
return {
message: "",
order: {},
},
methods: {
send: function() {
// here: `this` technically refers to the `methods` object
// but Vue lifts it to the entire view object at runtime
axios.post(this.api + "orders", this.order).then(response => {
// here: this refers to the same object as it does in `send` because
// `=>` functions capture their outer `this` reference statically.
this.message = "Your payment was successful";
});
}
}
}
或者更好
export default {
data() {
return {
message: "",
order: {},
},
methods: {
async send() {
const response = await axios.post(`${this.api}orders`, this.order);
this.message = "Your payment was successful";
}
}
}
请注意,在第二个示例中,它使用了 JavaScript 最近标准化的async/await
功能,我们已经完全抽象出对回调的需求,因此这一点变得没有意义。
我在这里建议它,不是因为它与你的问题有关,而是因为它应该是编写 Promise 驱动代码的首选方式,如果你有它可用,你可以根据你对其他语言功能的使用来做。使用 Promises 时,它会导致更清晰的代码。
然而,这个答案的关键点是this
参考的范围。