Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vue组件v-vue-onkeypress限制只能输入数字_onkeypress="return(/[\d]/.test(string.fromcharcode-CSDN博客 #84

Open
HenryTSZ opened this issue Oct 18, 2023 · 0 comments

Comments

@HenryTSZ
Copy link
Owner

https://blog.csdn.net/hope_It/article/details/103180158

需求

日常工作中,用Vue的时候,经常遇到input框只能输入数字的要求

可以用,onkeypress事件结合String.fromCharCode去实现

<el-input v-model="name" onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)));"/>

要兼容firefox,则要做兼容:

  <el-input v-model="name" onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode || event.which))) || event.which === 8"/>

但是input多了,并且其它地方都需要使用,所以,就准备写个directive方便使用

directive指令的代码实现

onkeypress.js

export default {
  bind: function(el, binding) {
    el.onkeypress = function(e) {
      const ev = e || event
      
      return (/[\d]/.test(String.fromCharCode(ev.keyCode || ev.which))) || ev.which === 8
    }
  }
}

index.js

import VueOnkeypress from './onkeypress.js'


const install = function(Vue) {
  Vue.directive('VueOnkeypress', VueOnkeypress)
}

if (window.Vue) {
  window.VueOnkeypress = VueOnkeypress
  Vue.use(install) 
}

VueOnkeypress.install = install
export default VueOnkeypress

局部使用

<el-input v-vue-onkeypress v-model="name"/>


import VueOnkeypress from '@/directive/vue_onkeypress/index.js'
export default {
  directives: {
    VueOnkeypress
  }
}

全局使用

import VueOnkeypress from 'src/directive/onkeypress/index'

Vue.directive('VueOnkeypress', VueOnkeypress);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant