Vue3+Vuetify中v-textfield确认密码规则报错:无法读取password
Vue3 + Vuetify 确认密码校验报错解决方法
问题现象
在Vue3+Vuetify开发中,给确认密码的v-textfield设置校验规则时,出现this.password为undefined的报错,每次输入字符时触发如下错误:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'password') at confirmPasswordRules
相关代码片段:
data: () => ({ // Credentials username: '', password: '', confirmPassword: '', passwordRules: [ (value) => { if (value?.trim().length > 0) return true else return 'Password is required.' }, ], confirmPasswordRules: [ (value) => { if (value?.trim().length > 0) { // TODO: ERROR (this.password is undefined) if(value === this.password) { return true } else return 'Passwords do not match.' } else return 'Confirm password is required.' }, ], }),
问题原因
data选项使用了箭头函数,箭头函数没有独立的this上下文,会捕获外层作用域的this,导致无法指向Vue组件实例,自然无法访问实例上的password变量。
解决方案
方案1:Options API下修改data为普通函数
将data的箭头函数改为普通函数,让this正确指向组件实例:
data() { return { // Credentials username: '', password: '', confirmPassword: '', passwordRules: [ (value) => { if (value?.trim().length > 0) return true else return 'Password is required.' }, ], confirmPasswordRules: [ (value) => { if (value?.trim().length > 0) { if(value === this.password) { return true } else return 'Passwords do not match.' } else return 'Confirm password is required.' }, ], } },
方案2:Composition API(
相关产品推荐
相关产品推荐

