1.1 plugins/myfocus.js
export default {
created(el, binding, vnode, prevVnode) {
// 下面会介绍各个参数的细节
}, // 在元素被插入到 DOM 前调用
beforeMount(el, binding, vnode, prevVnode) {}, // 在绑定元素的父组件及他自己的所有子节点都挂载完成后调用
mounted(el, binding, vnode, prevVnode) {
console.log(1111, el)
// el.querySelector('input').focus()
}, // 绑定元素的父组件更新前调用
beforeUpdate(el, binding, vnode, prevVnode) {}, // 在绑定元素的父组件及他自己的所有子节点都更新后调用
updated(el, binding, vnode, prevVnode) {}, // 绑定元素的父组件卸载前调用
beforeUnmount(el, binding, vnode, prevVnode) {}, // 绑定元素的父组件卸载后调用
unmounted(el, binding, vnode, prevVnode) {}
}
1.2 main.js
import myfocus from './directive.js'
const app = createApp(App)
app.directive('myfocus', myfocus)
2.1
<script setup>
import { ref, vModelText } from 'vue'
const value = ref('')
// 为' v-model '指令定义一个名为'capitalize '的自定义修饰符
vModelText.beforeUpdate = function (el, { value, modifiers }) {
console.log('modifiers:', modifiers)
// 检查' v-model '指令中是否存在' capitalize '修饰符
if (value && modifiers.capitalize) {
el.value = el.value.toUpperCase() //把小写转成大写
}
}
</script>
<template>
<input type="text" v-model.capitalize="value" />
</template>
export default {
install(app) {
app.directive(
'decryption',
(el, binding) => {
youMethod(el, binding.value)
}
// {
//指令的钩子会传递2个参数
//el:指令绑定到的元素,这可以用于直接操作 DOM
//binding.value:传递给指令的值
// mounted(el, binding) {
// DecryptionMethod(el, binding.value);
// },
// }
)
}
}