sourcecode

VueJs가 함수 내의 데이터 속성에 액세스할 수 없습니다.

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

VueJs가 함수 내의 데이터 속성에 액세스할 수 없습니다.

함수 내에서 데이터 속성에 액세스하는 데 문제가 있습니다.뭔가 놓친 게 있는데 뭐가 뭔지 모르겠어요.

이것은 나의 수업이다.

export default {
    name: "Contact",
    components: {
        FooterComponent: FooterComponent,
        NavigationComponent: NavigationComponent
    },
    data() {
        return {
            locale: Cookie.get('locale'),
            nameAndLastName: '',
            email: '',
            subject: '',
            message: '',
            showPopUp: false
        }
    },
    methods: {
        sendEmail(e) {
            e.preventDefault();
            this.$validator.validateAll();
            if (!this.$validator.errors.any()) {
                let params = new URLSearchParams();
                params.append('nameAndLastName', this.nameAndLastName);
                params.append('email', this.email);
                params.append('subject', this.subject);
                params.append('message', this.message);

                axios.post(this.$apiUrl + `rest/api/public/Contact/contact`, params, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                    .then(function (response) {
                        if (response.statusText === 'OK') {
                            console.log(this.showPopUp);
                            this.showPopUp = true;
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        // This throws error TypeError: Cannot read property 'showPopUp' of undefined

                    });
            }
        }
    },
    mounted: function () {
        console.log('test');
        console.log(this.showPopUp);
    },
}

문제는 메시지를 보낼 때 응답은 정상이고 이메일은 전송되지만 오류가 계속 발생한다는 것입니다.TypeError: Cannot read property 'showPopUp' of undefined...console.log(이것)를 인쇄하려고 합니다.마운트된 훅의 show Pop Up)에서 변수는 표시 OK인데 메서드에서 액세스할 수 없는 이유는 무엇입니까?VueJs 2를 사용하고 있습니다.

추가 정보가 필요하시면 알려주시면 알려드리겠습니다.감사해요!

this내면에.then()콜백은 찾고 있는 프록시 데이터가 아니라 콜백 자체를 의미합니다.

작동시키려면 올바른 값을 할당해야 합니다.this콘텍스트를 다른 변수로 변환한 후 이 변수를 사용합니다.

이렇게 코드를 조사합니다.

export default {
    name: "Contact",
    components: {
        FooterComponent: FooterComponent,
        NavigationComponent: NavigationComponent
    },
    data() {
        return {
            locale: Cookie.get('locale'),
            nameAndLastName: '',
            email: '',
            subject: '',
            message: '',
            showPopUp: false
        }
    },
    methods: {
        sendEmail(e) {
            var self = this: // assign context to self variable
            e.preventDefault();
            this.$validator.validateAll();
            if (!this.$validator.errors.any()) {
                let params = new URLSearchParams();
                params.append('nameAndLastName', this.nameAndLastName);
                params.append('email', this.email);
                params.append('subject', this.subject);
                params.append('message', this.message);

                axios.post(this.$apiUrl + `rest/api/public/Contact/contact`, params, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                    .then(function (response) {
                        if (response.statusText === 'OK') {
                            console.log(this.showPopUp);
                            self.showPopUp = true; // assign it like this
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        // This throws error TypeError: Cannot read property 'showPopUp' of undefined

                    });
            }
        }
    },
    mounted: function () {
        console.log('test');
        console.log(this.showPopUp);
    },
}

그래서...ES6화살표 기능은 매우 유용합니다.this여기서 설명하는 것은 기능 자체를 의미하는 것은 아닙니다.

따라서 다음과 같은 화살표 기능도 사용할 수 있습니다.

.then((response) => {
  if (response.statusText === 'OK') {
    console.log(this.showPopUp);
    this.showPopUp = true;
  }
})

언급URL : https://stackoverflow.com/questions/50527835/vuejs-cant-access-data-property-within-the-function

반응형