Vue组件使用正则校验邮箱时报Cannot set property 'value'错误如何解决
报错原因
document.getElementById返回的是单个DOM元素对象,不是DOM集合,你代码中使用spanMail[0]取索引的写法会得到undefined,对undefined设置value属性就会抛出该报错。- 额外补充:span标签属于普通文本标签,不存在value属性,就算你去掉[0]直接设置
spanMail.value也不会生效,需要用innerText/textContent属性设置文本内容。 - 你当前使用原生DOM操作的写法不符合Vue开发规范,若该组件被父组件多次引用,页面会出现多个重复id的元素,
getElementById只会匹配到第一个渲染的组件内元素,会导致后续组件的校验逻辑全部错乱。
解决方案
快速修复现有代码
直接修改checkInput方法内的逻辑即可:
methods:{ checkInput(){ const email = document.getElementById('inputMail'); const spanMail = document.getElementById('mailSpan'); // 改用箭头函数避免this指向问题 email.onkeydown = () => { const regex = /^([\.\_a-zA-Z0-9]+)@([a-zA-Z]+)\.([a-zA-Z]){1,8}$/; const regexo = /^([\.\_a-zA-Z0-9]+)@([a-zA-Z]+)\.([a-zA-Z]){1,3}\.[a-zA-Z]{1,3}$/; if(regex.test(email.value) || regexo.test(email.value)) { // 去掉[0],改用innerText设置span文本 spanMail.innerText = "Your email is valid"; spanMail.style.color= 'lime'; } else { spanMail.innerText = "Your email is invalid"; spanMail.style.color= 'red'; } } } }
推荐的Vue规范写法(更稳定,无DOM操作副作用)
采用Vue数据驱动的思路,不用手动操作DOM,自动响应输入变化:
模板部分修改
<template> <div class="row"> <div class="column"> <span>Emailadresse</span> </div> <div class="column column2"> <!-- 绑定v-model同步输入值到data --> <input v-model="email" type="text" placeholder="Bsp: franken@stein.öö"/> </div> <!-- 动态绑定样式和文本 --> <span :style="{color: tipColor}">{{emailTip}}</span> </div> </template>
逻辑部分修改
module.exports = { name: "Emaildaten Baustein", props: {}, data() { return { // 存储输入的邮箱 email: '', // 存储校验提示文本 emailTip: '', // 存储提示文本颜色 tipColor: '' } }, watch: { // 监听邮箱值变化,自动执行校验 email(newVal) { const regex = /^([\.\_a-zA-Z0-9]+)@([a-zA-Z]+)\.([a-zA-Z]){1,8}$/; const regexo = /^([\.\_a-zA-Z0-9]+)@([a-zA-Z]+)\.([a-zA-Z]){1,3}\.[a-zA-Z]{1,3}$/; if(regex.test(newVal) || regexo.test(newVal)) { this.emailTip = "Your email is valid"; this.tipColor = 'lime'; } else { this.emailTip = "Your email is invalid"; this.tipColor = 'red'; } } } };
内容的提问来源于stack exchange,提问作者FloHaberfellner
相关产品推荐
相关产品推荐

