简体   繁体   中英

Why keydown not working in mobile? vue.js 2

I try like this :

<template> 
    ...
    <input type="number" class="form-control" v-model="quantity" min="1" v-on:keydown="disableDot">
    ...                           
</template>
<script>
    export default{
        ...
        methods:{
            disableDot: function(evt) {
                evt = (evt) ? evt : window.event
                let charCode = (evt.which) ? evt.which : evt.keyCode
                if (charCode === 190 || charCode === 189 || charCode === 187) {
                    evt.preventDefault()
                } 
                else {
                    return true
                }
            }

        }
    }
</script>

If the code executed and I input dot(.), it still can

In dekstop, it had disable. But in mobile, it does not disable

I want to disable dot. So user can not input dot

How can I do it?

Note

In dekstop, the code works. But in mobile, the code does not works. The dot(.) no disable in mobile

The trouble is that the keycodes with 'keydown' or 'keyup' dont seem to be consistent across browsers. Maybe the OS has an affect as well. You can test this on various browsers and mobile devices here

I think you will find more consistency using the v-on:keypress event instead. The following in my quick (incomplete on mobile) testing returns '46' consistently. A quick warning, I noticed that typing '.' on firefox mobile on my android keyboard I was receiving two keypress events.

//in template
<input type="number"  v-on:keypress="capturePress($event)">

//in methods
capturePress: function(event) {
    console.log(event.charCode);
}

I would also encourage you to have a look at the whole event as it also returns. event.code = "Period" and event.key = "." though only event.key = "." was filled on mobile firefox.

console.log(event);

Using a watcher worked the best for me. It would be something like this:

<template> 
    ...
    <input type="number" class="form-control" v-model="quantity" min="1">
    ...                           
</template>
<script>
    export default{
        ...
        methods:{
            disableDot: function(evt) {
                evt = (evt) ? evt : window.event
                let charCode = (evt.which) ? evt.which : evt.keyCode
                if (charCode === 190 || charCode === 189 || charCode === 187) {
                    evt.preventDefault()
                } 
                else {
                    return true
                }
            }

        }

        watch: {
          "quantity"(value) {
            this.disableDot();
          }
        },
    }
</script>

我发现了 android 设备的真正问题,您应该像这样禁用表单的自动完成功能:

 <form autocomplete="off" action="/action_page.php">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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