【问题标题】:VueJs can't access data property within the functionVueJs 无法访问函数内的数据属性
【发布时间】:2018-11-04 18:32:46
【问题描述】:

我在访问函数内的数据属性时遇到问题。我错过了一些东西,我不知道是什么。

这是我的课

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);
    },
}

所以问题是当我发送消息时,响应正常,发送电子邮件,但是当我尝试在挂载的钩子中打印 console.log(this.showPopUp) 时,我一直收到错误TypeError: Cannot read property 'showPopUp' of undefined... ,变量显示正常,为什么我不能从方法中访问它?我正在使用 VueJs 2。

如果您需要任何其他信息,请告诉我,我会提供。谢谢!

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    .then() 回调中的 this 指的是回调本身,而不是您要查找的代理数据。

    为了使其工作,您需要将正确的 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;
      }
    })
    

    【讨论】:

    • 当然!!! :D 天哪,这困扰了我很长一段时间。或者我可以简单地将 .then(function .... 更改为 .then((response) => { 我可以使用这个... :D 傻我! :D
    • 另一种可能的方法是使用Function.prototype.bind(developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)
    • @Valor_ 完全正确。我刚刚用箭头函数方法编辑了答案。我能感觉到你。之前发生在我身上好几次
    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 2020-10-20
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多