【问题标题】:How to get Regex through other components?如何通过其他组件获取Regex?
【发布时间】:2021-11-17 15:50:47
【问题描述】:

我的 Vue 应用程序有点问题。

这里有一个名为 Module1.vue 的 .vue 文件,用户必须在其中输入电子邮件地址。

<template>
<div class="row">
 <div class="column">
  <span>Emailadresse</span>
 </div>
 <div class="column column2">
  <input id="inputMail" type="text" placeholder="Bsp: franken@stein.öö"/>
 </div>
 <span ref="mailSpan1" id="mailSpan"></span>
</div>

</template

然后我创建了一个方法来检查电子邮件格式的正确性。并在电子邮件有效与否时显示。

module.exports = {
  name: "Emaildaten Baustein",
  props: {},
  data() {
  },
  methods:{
    checkInput(){
        let email = document.getElementById('inputMail');
        let spanMail = document.getElementById('mailSpan');

        email.onkeydown = function(){
        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))
        {
          spanMail[0].value="Your email is valid";
          spanMail[0].style.color= 'lime';
        }
        else
        {
          spanMail[0].value="Your email is invalid";
          spanMail[0].style.color= 'red';
        }
      }
    }
  },
  mounted(){
    this.checkInput();
  }
};

现在当我运行我的应用程序并输入一些内容时,我收到了这个错误:

Uncaught TypeError: Cannot set property 'value' of undefined
    at HTMLInputElement.email.onkeydown (eval at C (httpVueLoader.js:86), <anonymous>:32:29)

供您参考:我在另一个组件中使用了这个 Module1.vue 组件。这看起来像这样:

<template>
 <header-component></header-component>
 <email-component></email-component> //Module1.vue
 <footer-component></footer-component>
</template>

【问题讨论】:

    标签: javascript html regex vue.js


    【解决方案1】:

    我认为问题出在这里:

    spanMail[0].value="Your email is valid";
    

    你正在初始化你的 spanMail 变量:

    let spanMail = document.getElementById('mailSpan');
    

    并且getElementById(id) 返回一个实际的Element,而不是Elements 的列表。所以你的代码应该更像:

    spanMail.value="Your email is valid";
    

    【讨论】:

    • 这会引发完全相同的错误
    • 如果将spanMail 的初始化移动到onkeydown 处理程序中会发生什么?也许checkInput 运行得早,'mailSpan' 尚不可用。
    • 然后我每次按键盘上的键时都会再次收到相同的错误
    【解决方案2】:

    我已经发现了错误。你做不到

    spanMail[0].value="Your email is valid";
    

    我做了

    spanMail.textContent="Your email is valid";
    

    【讨论】:

      猜你喜欢
      • 2021-09-27
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多