2019년 4월 12일 금요일

vue axios 내부 함수 호출

vue에서 REST 요청을 위해서 axios를 많이 활용 한다.

jQuery에서 $.get(), $.post 와 같이 vue에서는 axios.get()으로 쓴다.

틀은 다음과 같음

axios.get('url')
 .then(response => {
 //응답 처리

 })
 .catch(error => {
 //에러 처리

 });

!then 문에서 methods에 정의된 함수를 호출할 경우 Reference Error가 발생 할 수 있다.
=> 해결 방법은 axios 호출 전에 this를 임시 변수에 넣고 해당 변수를 활용하는 방법으로 해결 할 수 있다. (아래 코드 참조)


let self = this
    
axios.get('url')
   .then(response => {
      response.data.forEach(function(value){
        value.a = self.innerMethod(value.a) //  Reference Error 발생 부분, this대신 self로 대체
      });
      self.a = response.data // data 또한 self로 접근
   })
   .catch(error => {
        console.log(error.response);
   });

댓글 없음:

댓글 쓰기