sourcecode

vue의 콜백에서 로컬 컴포넌트 변수에 액세스하는 방법

copyscript 2022. 8. 13. 12:23
반응형

vue의 콜백에서 로컬 컴포넌트 변수에 액세스하는 방법

api rest 명령을 사용하여 컴포넌트 변수를 설정하려고 합니다.아래의 handleResponse()라는 자체 파일에 있는 함수를 통해 모든 응답을 처리하고 싶었습니다.

// api/tools/index.js
function handleResponse (promise, cb, cbError) {
  var cbErrorRun = (cbError && typeof cb === "function") 

  promise.then(function (response) {
    if (!response.error) {
      cb(response)
    }
    else if (cbErrorRun) {
      cbError(response)
    }
  }).catch(function (error) {
    console.log(error)
    if (cbErrorRun) {
      var responseError = {
        "status": 404,
        "error": true,
        "message": error.toString()
      }
      cbError(responseError)
    }
  })
}
export {handleResponse}

내 컴포넌트 파일에 이 파일이 있습니다.

.... More above....
<script>
import { fetchStock } from '@/api/stock'    

  export default {

    data () {
      return {
        stock: {},
        tabs: [
          {
            title: 'Info',
            id: 'info'
          },
          {
            title: 'Listings',
            id: 'listings'
          },
          {
            title: 'Company',
            id: 'company'
          }
        ],
      }
    },
    validate ({params}) {
      return /^\d+$/.test(params.id)
    },
    created: function() {
      var params = {'id': this.$route.params.stockId}
      //this.$route.params.stockId}
      fetchStock(
        params,
        function(response) { //on successful data retrieval
          this.stock = response.data.payload // payload = {'name': test123}
          console.log(response)
        },
        function(responseError) { //on error
          console.log(responseError)
        }
      )
    }
  }
</script>

현재 코드는 다음과 같은 오류를 표시합니다. "Uncatched (in promise)"TypeError: undefinedAc의 속성 'stock'을 설정할 수 없습니다.fetchStock 함수로 전달한 콜백 내에서 더 이상 'this'에 액세스할 수 없기 때문에 발생하는 현상이라고 생각합니다.현재 handleResponse 레이아웃을 변경하지 않고 이 문제를 해결하려면 어떻게 해야 합니까?

이 방법을 시도해 보세요.

  created: function() {
      var params = {'id': this.$route.params.stockId}
      //this.$route.params.stockId}
      var self = this;
      fetchStock(
        params,
        function(response) { //on successful data retrieval
          self.stock = response.data.payload // payload = {'name': test123}
          console.log(response)
        },
        function(responseError) { //on error
          console.log(responseError)
        }
      )
    }

화살표 함수는 다음을 유지 및 사용하기 때문에 화살표 함수를 콜백에 사용할 수 있습니다.this포함 범위:

created: function() {
      var params = {'id': this.$route.params.stockId}
      //this.$route.params.stockId}

      fetchStock(
        params,
        (response) => { //on successful data retrieval
          self.stock = response.data.payload // payload = {'name': test123}
          console.log(response)
        },
        (responseError) => { //on error
          console.log(responseError)
        }
      )
    }

또는 할당할 수 있습니다.const vm = thisn 이와 같은 콜백 전에 메서드를 시작합니다.

vm은 "View Model"을 나타냅니다.

  created: function() {
      var params = {'id': this.$route.params.stockId}
      //this.$route.params.stockId}
      const vm = this;
      fetchStock(
        params,
        function(response) { //on successful data retrieval
          self.stock = response.data.payload // payload = {'name': test123}
          console.log(response)
        },
        function(responseError) { //on error
          console.log(responseError)
        }
      )
    }

를 사용하는 것을 권장합니다.const와는 반대로var에서vm가치를 분명히 하기 위한 선언vm상수입니다.

언급URL : https://stackoverflow.com/questions/50313922/how-to-access-local-component-variable-from-a-callback-in-vue

반응형