简体   繁体   English

我怎样才能使@blur事件正常工作-Nuxtjs

[英]how can i to make @blur event work properly - Nuxtjs

I am trying to trigger a function that validates an input field when it loses focus using nuxtjs.我正在尝试触发一个 function,它在使用 nuxtjs 失去焦点时验证输入字段。 When I focus out of the input field, the function isn't triggered but gets triggered when I focus in and start typing in another or the same input field.当我关注输入字段时,function 不会被触发,但当我关注并开始在另一个或同一个输入字段中输入时会被触发。

<div class="control">
  <input class="input" type="text" ref="email" @blur="validateMail()" v-model="email_p" name="email" />
</div>

this is the function call这是 function 电话

 methods: {
        validateMail(){
            let value = this.$refs.email.value
            let mailformat = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

            if (value.match(mailformat)) {
                //validation passed
            } else {
                this.msg.email = 'Enter a valid email';
            }
        },
}

This may work fine这可能工作正常

<template>
  <div class="control">
    <input
      ref="email"
      v-model="email_p"
      class="input"
      type="text"
      name="email"
      @blur="validateMail"
    />
    message: {{ msg.email }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      email_p: '',
      msg: {
        email: '',
      },
    }
  },
  methods: {
    validateMail(value) {
      const mailformat =
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

      if (value.target.value.match(mailformat)) {
        // validation passed
      } else {
        this.msg.email = 'Enter a valid email'
      }
    },
  },
}
</script>

You don't need to use $refs to access the element, you can access the event directly.您不需要使用$refs来访问元素,您可以直接访问事件。
If you want to get the value via $refs , you would need to wait for a full tick to trigger , to get the actual new value.如果你想通过$refs获取value ,你需要等待一个完整的tick来触发,以获取实际的新值。 Hence use the event passed by @blur , simpler, cleaner and less messy.因此,使用@blur传递的event ,更简单、更干净、更整洁。

Also, value.target.value is important because it's receiving an event and not the HTML element itself.此外, value.target.value很重要,因为它正在接收一个事件,而不是 HTML 元素本身。

PS: the event can also be written as @blur="validateMail($event)" if you want to be more explicit but it's not mandatory (it's passing it by itself already). PS:事件也可以写成@blur="validateMail($event)"如果你想更明确但它不是强制性的(它已经自己传递了)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM