我在VueJs中的一些组件看起来像这样:
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);
}
}
}
当触发validateObject方法并且我试图访问表单对象的嵌套属性时,我得到can not read property 'child' of undefined
错误。在控制台中进行debbuging时,我可以看到表单不是常规对象,而是{__ob__: Observer}
答案 0 :(得分: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
}
}
这看起来更好,更具可读性。 不要使用函数
submit: () => {}
正确的方式来访问'this'是:
submit() {}