外观
输入框限制输入数字指令
封装 Vue 指令实现 <input type="number" />。
自定义指令主要是为了复用涉及 DOM 操作的逻辑。
指令钩子
一个自定义指令用一个对象来定义,该对象包含了跟组件类似的生命周期钩子:
- created:指令首次绑定到元素时调用,此时元素属性和事件还未应用,元素尚未插入页面。
- beforeMount:元素被插入 DOM 前调用。
- mounted:元素的父组件及其所有子组件都挂载完成后调用,此时元素已插入 DOM。
- beforeUpdate:元素的父组件及其子组件更新前调用。
- updated:元素的父组件及其子组件更新后调用。
- beforeUnmount:元素的父组件卸载前调用。
- unmounted:元素的父组件卸载后调用。
这些生命周期函数都会接收到三个参数:el、binding 和 vnode,分别为指令绑定的 DOM 元素、一个包含指令参数和值的对象、对应的虚拟节点。
v-number-input 自定义指令
Vue3 中 v 开头的小驼峰命名变量将成为自定义指令,在 mounted 周期为 <input> 元素绑定 input 事件,事件触发时将输入的非数字字符串剔除,以实现只能输入数字的功能。
js
const vNumberInput = {
mounted(el, binding, vnode) {
const input = el.nodeName === 'INPUT' ? el : el.querySelector('input')
input.addEventListener('input', inputHandle(el, binding, vnode), false)
},
beforeUnmount(el) {
const input = el.nodeName === 'INPUT' ? el : el.querySelector('input')
input.removeEventListener('input', inputHandle(el, binding, vnode), false)
}
}
function inputHandle(el, binding, vnode) {
return function () {
const elValue = el.value
// 去掉数字和负号以外的字符
elValue = elValue.replace(/[^\d-]/g, '')
// 去掉非首位的负号
elValue = elValue.replace(/(?!^)[-]/g, '')
el.value = elValue
}
}指令修饰符
当前只能输入正负整数,可使用修饰符来表示可输入小数。一个指令完整语法为:

如图所示可用一个具体事件绑定来记忆: @click.native="handle",@ 是 v-on 简写,所以分别为指令名、指令参数、修饰符和指令值。
指令参数、修饰符和指令值保存在了 binding 对象中,以 @click.native="handle" 为例:
- arg:指令参数,为
"click"。 - modifiers:修饰符对象,为
{ native: true },有多个修饰符则对象有多个对应属性名。 - value:指令值,为
handle。
小数和小数位数
添加 float 修饰符表示可输入小数,同时指令的值作为小数位数。
js
function inputHandle(el, binding, vnode) {
return function () {
let elValue = el.value
const isFloat = binding.modifiers.float
const illegalReg = isFloat ? /[^\d.-]/g : /[^\d-]/g
// 去掉非法字符
elValue = elValue.replace(illegalReg, '')
// 去掉不是首位的负号
elValue = elValue.replace(/(?!^)[-]/g, '')
if (isFloat) {
// 去掉第一个小数点外的小数点
elValue = elValue.replace(/^([^.]*\.[^.]*)\./g, '$1')
// 首位是小数点则添加前置 0
elValue = elValue.replace(/(?=^)[.]/g, '0.')
// 保留指定小数位数
const places = Number(binding.value)
const dotIndex = elValue.indexOf('.')
if (typeof places === 'number' && dotIndex !== -1) {
const lastIndex = dotIndex + places + 1
elValue = elValue.substring(0, lastIndex)
}
}
el.value = elValue
}
}最后直接在输入框上使用指令: <input v-number-input />。
与 Vue2 差别
Vue2 与 Vue3 指令的生命周期名称不同:
- bind:指令绑定到元素,但元素未插入 DOM。
- inserted:元素插入父节点时调用。
- update:所在组件更新时调用。
- componentUpdated:指令所在组件及其子组件全部更新后调用。
- unbind:指令元素解绑时调用。
在 inserted 钩子中注册事件,在 unbind 钩子中解绑事件即可。