programing

Vue JS의 Axios 약속 내에서 속성을 설정할 수 없습니다.

copyandpastes 2022. 8. 16. 21:53
반응형

Vue JS의 Axios 약속 내에서 속성을 설정할 수 없습니다.

VueJs와 Axios를 사용하여 Larabel 백엔드에 HTTP 요청을 하여 JSON을 취득하고 JSON을 사용하여 컴포넌트의 errorMessage 속성을 업데이트하려고 합니다.

            Axios.post('/api/login', {
                email: this.email,
                password: this.password
            }).then((response) => {
                this.errorMessage = response.message;
            }).catch((error) => {
                console.error(error);
            })

문제는 이 정보를 참조할 수 없다는 것입니다.this.errorMessage무슨 이유에선지, 내가 뭘 잘못하고 있는 거야?HTTP 요청을 올바르게 작성하면 JSON 응답이 예상대로 반환됩니다.console.log하지만 제가 이 모든 걸 조작하려고 할 때this.errorMessage이미 다른 곳에서 성공적으로 조작했는데도 정의되지 않았다고 합니다.

다음은 이 구성 요소의 전체 코드입니다.

export default {
    methods: {
        submitForm: function(e) {
            e.preventDefault();

            Axios.post('/api/login', {
                email: this.email,
                password: this.password
            }).then((response) => {
                debugger;
                this.errorMessage = response.data.message;
            }).catch((error) => {
                console.error(error);
            });
        }
    },
    data: function() {
        return {
            errorMessage: null,
            email: null,
            password: null
        }
    },
    components: {
        'error': Error
    }
}   

해결책:

원래 요청은 정확하며, 팻 화살표 함수는 다음 값을 유지해야 합니다.this, Chrome의 Debugger에 문제가 있었습니다.이 Debugger는 그 값을 다음과 같이 표시했습니다.undefined그들이 아니었음에도 불구하고...바보 같은 질문 죄송합니다, 이런 문제를 접하게 된 다른 사람들에게 도움이 되었으면 합니다.

Axios.post은 가까운 함수이기 때문에 그 안에서 속성을 정의하는 것은 가까운 함수 아래 프라이빗한 것처럼 보입니다.

다음과 같이 외부 변수를 더 가깝게 정의해야 합니다.

//this will pick your data.
let self = this;


Axios.post('/api/login', {
     email: this.email,
     password: this.password
  }).then((response) => {
  self.errorMessage = response.message;
            }).catch((error) => {
                console.error(error);
            })

또, 만약response.message정의되어 있지 않습니다.response.body.message또는 라라벨에서 돌아오는 변수입니다.

응답 데이터는 다음에서 사용할 수 있습니다.data속성:

this.errorMessage = response.data.message;

언급URL : https://stackoverflow.com/questions/42369688/cant-set-property-inside-of-axios-promise-in-vue-js

반응형