1

I've some component in VueJs that looks like this:

export default {
    name: 'RecruitForm',
    data() {
        return {
            form: {
                child: {},
                mother: {},
                father: {}
            },
            isSubmiting: false,
            isValid: true
        }
    },
    methods: {
        submit: () => {
            this.isSubmiting = true;
            this.isValid = true;
            let validateObject = (obj) => {
                var keys = Object.keys(obj);
                if(keys.length === 0){
                    return false;
                }

                for (var key in keys) {
                    if (!this.form[key])
                        isValid = false;
                }
            }
            validateObject(this.form.child);
            validateObject(this.form.mother);
            validateObject(this.form.father);
        }
    }
}

When the validateObject method is fired and I'm trying to access nested properties of form object I get can not read property 'child' of undefined error. While debbuging in console I can see that the form is not regular object but {__ob__: Observer}

Paulie
  • 121
  • 2
  • 14
  • 1
    Possible duplicate of [VueJS: why is "this" undefined?](https://stackoverflow.com/questions/43929650/vuejs-why-is-this-undefined) – thanksd Aug 08 '17 at 20:11
  • Change `submit: () => {` to `submit() {`. See the post linked above for an explanation – thanksd Aug 08 '17 at 20:16

1 Answers1

2
name: 'RecruitForm',
data() {
    return {
        form: {
            child: {},
            mother: {},
            father: {}
        },
        isSubmiting: false,
        isValid: true
    }
},
methods: {
    submit(){
        this.isSubmiting = true;
        this.validateObject();
    },
    validateObject(){
        this.isValid = false
        if (!this.from.child || !this.drom.mother || !this.form.father) {
            return
        }
        this.isValid = true
    }    
}

this looks better and more readable. don't use function as

submit: () => {}

correct way in order to access 'this' is:

submit() {}
Sajed
  • 445
  • 1
  • 8
  • 19