全局自定义指令
场景: 视情况而定 (一般不使用)
// 全局自定义指令
app.directive('focus', {
mounted(el) {
el.focus();
}
})
app.directive('blur', {
mounted(el) {
el.addEventListener('blur', function(el) {
if (el.target.tagName === 'INPUT') {
el.target.value = el.target.value.toUpperCase();
}
})
}
})
使用方式:template直接使用: <input v-focus v-blur />
局部自定义指令
const directives = {
focus: {
mounted(el) {
el.focus();
}
},
blur: {
mounted(el) {
el.addEventListener('blur', function(el) {
if (el.target.tagName === 'INPUT') {
el.target.value = el.target.value.toUpperCase();
}
})
}
}
}
使用方式
const app = Vue.createApp({
directives: directives, // 需要注册
template: `
<div>
<input v-focus v-blur />
</div>`,
})