从Axios访问VUE JS的数据 [英] Accessing VUE JS's data from Axios

查看:94
本文介绍了从Axios访问VUE JS的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Vue JS(Vuetify)应用程序,该应用程序发出ajax请求,我想用响应填充div的内容,但是我很难访问实例的数据.我看到的所有示例都使用 this 指向数据对象,但是当我收到此错误时

I have a Vue JS (Vuetify) App that makes an ajax request that I would like to populate a div's content with the response, however I am having difficulties accessing the instance's data. All examples I have seen use this to point to the data object, but when I do I get this error

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

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时遇到了问题.消息,与我所看到的示例相反.

this.order is accessible without a problem with Axios' post method however the anonymous function that handles the promise returned seems to have a problem accessing this.message, in contrary to the examples I have seen.

我在这里做不同的事情是什么?

What is it that I am doing differently here?

推荐答案

我可以为您的问题考虑这些解决方案.

I can think of these solutions for your problem.

1)您可以创建对this的引用并使用它.

1) You can create a reference to this and use it.

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

2)arrow function将使您能够使用this它将指向您的Vue实例.

2) An arrow function will enable you to use this which will point to your Vue instance.

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

3)使用bindthis分配一个对象,该对象将是您当前的Vue实例.

3) Use bind to assign an object to this which will be the current Vue instance in your case.

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

这篇关于从Axios访问VUE JS的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆