自定义指令详解, 直接上代码讲解可能更明白一点
整个页面的目录如下
utils
util.js
directives.js
pages
HelloWorld.vue
directives.js中是具体的逻辑代码
/* eslint-disable */
let inputNumber = {
inserted: function(el, binding) {
let e = el.querySelector('input')
let digit = binding.value || 3
let reg = new RegExp('^\\d*(\\.?\\d{0,' + digit + '})')
e.onkeyup = function (event) {
event.target.value = (event.target.value.match(reg)[0]) || null
}
}
};
let focus = {
inserted: function (el, binding) {
el.style = 'color:' + binding.value
}
}
export {inputNumber, focus}
util.js中是统一管理分步的方法
/* eslint-disable */
import Vue from 'vue';
import * as directives from './directives'
export default {
registerGlobalFun: function () {
Object.keys(directives).forEach(item => {
Vue.directive(item, directives[item])
})
}
}
HelloWorld.vue是具体的使用
<template>
<div class="hello">
<div v-inputNumber>
<input
type="text"
/>
</div>
</div>
</template>
<script>
import util from '@/utils/util'
util.registerGlobalFun()
export default {
name: 'HelloWorld',
data () {
return {}
}
}
</script>
网友评论