programing

Axios에서 VUE JS 데이터 액세스

goodcopy 2022. 8. 13. 23:33
반응형

Axios에서 VUE JS 데이터 액세스

vue JS(Vuetify) 앱에서 div의 콘텐츠를 응답으로 채우고 싶다는 Ajax 요청을 하는데 인스턴스의 데이터에 액세스하는 데 어려움이 있습니다.지금까지 본 예에서는 모두 데이터 개체를 가리키는데 이 오류가 발생합니다.

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

앱은 매우 간단합니다.

main.filename:

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";
        ...
      }
   }
 }

이.orderAxios의 post method로 문제없이 접근할 수 있지만, 반환된 약속을 처리하는 익명 함수는 제가 본 예와 달리 이.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) ANarrow function를 사용할 수 있습니다.thisVue 인스턴스를 가리킵니다.

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당신이 생각하는 것보다 더요.

기본적으로는sendVue 객체의 메서드입니다만,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 기반 코드를 작성할 때 선호되는 방법이어야 하기 때문입니다.다른 언어 기능을 사용하여 코드를 작성할 수 있는 경우입니다.Promise를 사용하면 코드가 명확해집니다.

단, 이 답변의 요점은 이 답변의 범위입니다.this언급.

언급URL : https://stackoverflow.com/questions/45216998/accessing-vue-jss-data-from-axios

반응형