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

查看:13
本文介绍了从 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

<代码>无法设置未定义或空引用的属性消息"

该应用程序非常简单:

ma​​in.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) 箭头函数将使您能够使用 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) 使用 bind 将一个对象分配给 this,这将是您的案例中的当前 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天全站免登陆