Vue 一個簡單的表單驗證指令

第一步:vue

  寫一個全局的插件  globle.js  並添加個Vue指令  v-validate  , 並在其中定義驗證規則,以下,添加了輸入字數限制和僅支持輸入數字校驗app

 1 function install(Vue, options) {
 2   // v-max
 3   Vue.directive('validate', function (el, arg) {
 4     const validate = {
 5       init: function (params) {
 6         params.maxlength && this.maxlength(params.maxlength)
 7         params.number && this.onlyNumber()
 8       },
 9       maxlength: function (max) {
10         el.addEventListener('input', function () {
11           el.value.length > max && (el.value = el.value.slice(0, max))
12         })
13       },
14       onlyNumber: function () {
15         let func = function () {
16           el.value = el.value.replace(/[^\d]/g,'')
17         }
18         el.addEventListener('keydown', func)
19         el.addEventListener('blur', func)
20         el.addEventListener('change', func)
21         el.addEventListener('input', func)
22       },
23 
24     }
25     validate.init(arg.value)
26   })
27 }
28 
29 export default install

第二步:this

       mian.js 中引入並  use spa

1 import Vue from 'vue'
2 import App from './App.vue'
3 import Globle from './plugin/globle'
4 Vue.config.productionTip = false
5 Vue.use(Globle)
6 new Vue({
7   render: h => h(App),
8 }).$mount('#app')

第三步:插件

  在頁面中使用,能夠看出校驗規則是在  v-validate  指令的參數中傳入的,須要用到什麼指令就添加對應的參數code

<input type="text" v-validate="{maxlength: 11}" placeholder="限制成11位"/>
<input type="text" v-validate="{number: true}" placeholder="限制成純數字">
<input type="text" v-validate="{number: true, maxlength: 11}" placeholder="限制成11位的純數字">

 

以上!blog

相關文章
相關標籤/搜索