从 Axios 访问 VUE JS 的数据



我有一个 Vue JS (Vuetify( 应用程序,它发出一个 ajax 请求,我想用响应填充div 的内容,但是我在访问实例的数据时遇到困难。我看到的所有示例都使用它来指向数据对象,但是当我这样做时,我会收到此错误

Unable to set property 'message' of undefined or null reference

该应用程序非常简单:

主.js

import Vue from 'vue'
import App from './App.vue'
import Vuetify from 'vuetify'

Vue.use(Vuetify)
new Vue({
el: '#app',
render: h => h(App)
})

App.vue

export default {
data () {
return {
....
message: '',
order: {},
...
},
methods: {
send: function() {
axios.post(this.api+"orders",this.order).then(function(response) {
this.message = "Your payment was successful";
...
}
}
}

this.order可以通过Axios的post方法访问而不会出现问题,但是处理返回的承诺的匿名函数似乎在访问this.message时出现问题,这与我看到的示例相反。

我在这里做什么不同?

我可以为您的问题想到这些解决方案。

1( 您可以创建对this的引用并使用它。

send: function() {
let self = this
axios.post(this.api + "orders", this.order).then(function(response) {
self.message = "Your payment was successful"
}
}

2( 一个arrow function将使您能够使用指向您的 Vue 实例的this

send: function() {
axios.post(this.api + "orders", this.order).then(response => {
this.message = "Your payment was successful"
}
}

3( 使用bind将一个对象分配给this该对象将成为您案例中的当前 Vue 实例。

send: function() {
axios.post(this.api + "orders", this.order).then(function(response) {
this.message = "Your payment was successful"
}.bind(this))
}

你的问题是这一行

axios.post(this.api+"orders",this.order).then(function(respo‌​nse) {

示例可以使用this,但是,通过使用第二级嵌套函数表达式,您正在访问与您想象的不同动态this

基本上,send是 Vue 对象的方法,但由于this不是在function表达式内部的词法范围内,而是在=>函数内部,因此您在传递给Promise.prototype.then的回调中引用了错误的this

以下是细分:

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 驱动代码的首选方式,如果您根据您对其他语言功能的使用来使用它。使用承诺时,它会导致更清晰的代码。

然而,这个答案的关键点是this参考的范围。

最新更新