【发布时间】:2017-12-26 06:51:38
【问题描述】:
我有一个 Vue JS (Vuetify) 应用程序,它发出一个 ajax 请求,我想用响应填充 div 的内容,但是我在访问实例的 数据 时遇到了困难。我见过的所有示例都使用 this 指向数据对象,但是当我这样做时,我得到了这个错误
Unable to set property 'message' of undefined or null reference
应用程序非常简单:
main.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 时出现问题。消息,与我看到的例子相反。
我在这里做的不同是什么?
【问题讨论】:
-
你的问题是这行
axios.post(this.api+"orders",this.order).then(function(response) {。示例可能会使用 this,但是通过使用第二个嵌套的function表达式,您访问的动态 this 与您认为的不同。将=>函数传递给.then。基本上,.send是 vue 对象的方法,但由于this不是function表达式内部的词法范围,仅在=>函数内部,你的回调中有错误的this引用。 -
Axios can't set data的可能重复
标签: javascript vuejs2 axios lexical-closures vuetify.js