Home > Blockchain >  Vue.js - Watch the input value has been changed or not
Vue.js - Watch the input value has been changed or not

Time:10-15

I am newcomer in Vue.js. Currently, I am creating a validation dialog to see user's otp is valid or not. If the value has not been changed over 5 seconds, my application disconnects automatically. However, if I use watch to monitor the value, it didn't work because the value is not changed, watch does not trigger.

How can I monitor the value is not changed within 5 seconds?

Dialog

<template>
 <div>
  <input type="text" v-model="otp">
  <b-button size="md" @click="cancel()" class="jump-to-ada-btn-cancel">
    Cancel
  </b-button>
  <b-button size="md" @click="handleJumpPage()" class="jump-to-ada-btn">
    Send
  </b-button>
 </div>
</template>

<script>

export default {
  data () {
    return {
      otp: ""
    }
  },
  computed: {
    show: {
      get: function () {
        return this.$store.state.modals.showOTPModal
      },
      set: function (val) {
        this.$store.commit("OPEN_OTP", {fieldName: "showOTPModal", fieldValue: val})
      }
    }
  },
  methods: {
    checkValueChange(newValue) {
      if(newValue === "") {
        alert("value is not changed yet")
      }
    }
  },
  watch: {
    otp: function(v) {
      console.log(v)
      let self = this
      setTimeout(function() {
        self.checkValueChange(v)
      }, 5000)
    }
  }
}
</script>

CodePudding user response:

You do not need to watch the otp value to implement that. You only need to check if the value of the otp data property is empty in a setTimeout callback. You can add it inside handleJumpPage method (which is missing from your code above):

setTimeout(() => {
  if (this.otp === "") {
     // disconnect
  }
}, 5000)

EDIT

If you want to add a timeout that checks if otp has changed 5 seconds since component mounting you can add an extra flag as data property and check its value:

data: {
   otp: "",
   otpUpdated: false
},
watch: {
   otp() {
      otpUpdated = true
   }
},
mounted() {
  setTimeout(() => {
     if (!this.otpUpdated) {
       // disconnect
     }
   }, 5000)
}

CodePudding user response:

Assuming that you start the 5 second countdown, as soon as the user visits the page. You'll need to start the countdown when the page is loaded. You can do that using the mounted lifecycle hook.

mounted: function() {
 setTimeout(() => {
  this.checkValueChange(this.otp)
 }, 5000)
}

Code sandbox link - https://codesandbox.io/s/damp-snowflake-tovs2

  • Related