大米饭来啦,分享一下最近新学习到的知识
最近开发需要用到自定义指令去处理需求,需求是进行权限控制,了解到需要进行控件、页面方面的权限功能点,就想到了自定义指令,但是之前没有接触过自定义指令,于是开启了研究+开发
之前所了解到的是vue2相关的指令,现在要写的vue3指令,最近才知道在自定义指令方面有它自己的生命周期钩子,和vue本身的组件生命周期钩子不同,先从钩子的角度来讲一下,也可以直接看官网 官网解释
自定义指令是直接操作元素DOM的,所以一般涉及到DOM的情况可以使用自定义指令,比如权限点的控制、输入框聚焦的情况等
先列一下vue2的自定义指令
bind - 指令绑定到元素后调用。只调用一次。
inserted - 元素插入父 DOM 后调用。
update - 当元素更新,但子元素尚未更新时,将调用此钩子。
componentUpdated - 一旦组件和子级被更新,就会调用这个钩子。
unbind - 一旦指令被移除,就会调用这个钩子。也只调用一次。
vue3的自定义指令
created - 新增!在元素的 attribute 或事件监听器被应用之前调用。
bind → beforeMount
inserted → mounted
beforeUpdate:新增!在元素本身被更新之前调用,与组件的生命周期钩子十分相似。
update → 移除!该钩子与 updated 有太多相似之处,因此它是多余的。请改用 updated。
componentUpdated → updated
beforeUnmount:新增!与组件的生命周期钩子类似,它将在元素被卸载之前调用。
unbind -> unmounted
3和2的区别主要是3更靠近组件生命周期了,和2有很大的不同,先大概写一个代码例子,下面是3的代码实例,也是自己项目中所使用的,可以依次为基础进行封装。
mport type { DirectiveBinding, Directive } from 'vue'
const directive: Directive = {
/* 新增!在元素的 attribute 或事件监听器被应用之前调用。 */
created(el: HTMLElement, binding: DirectiveBinding, vnode: any) {
console.log(el, binding, vnode, 'created')
},
/* 新增 指令被绑定在元素上使用 */
beforeMount(el: HTMLElement, binding: DirectiveBinding, vnode: any) {
console.log(el, binding, vnode, 'beforeMount')
},
/* 被绑定的元素插入DOM元素时调用 */
mounted(el: HTMLElement, binding: DirectiveBinding, vnode: any) {
console.log(el, binding, vnode, 'mounted')
},
/* 新增 在元素本身被更新之前调用,与组件的生命周期钩子相似*/
beforeUpdate(el: HTMLElement, binding: DirectiveBinding, vnode: any) {
console.log(el, binding, vnode, 'beforeUpdate')
},
/* 新增 所在组件的 VNode 及其子 VNode 全部更新后调用 */
updated(el: HTMLElement, binding: DirectiveBinding, vnode: any) {
console.log(el, binding, vnode, 'updated')
},
/* 元素被卸载之前调用 */
beforeUnmount(el: HTMLElement, binding: DirectiveBinding, vnode: any) {
console.log(el, binding, vnode, 'beforeUnmount')
},
/* 新增 元素卸载之后调用 */
unmounted(el: HTMLElement, binding: DirectiveBinding, vnode: any) {
console.log(el, binding, vnode, 'unmounted')
}
}
export default directive
注册自定义指令的相关插件,暴露出去install方法,可以直接使用app.use进行注册,进而全局使用
import type { App } from 'vue'
import hasPerm from './permission/hasPerm'
import hasRole from './permission/hasRole'
export default {
/* 暴露出去install方法,便于app.use(permission)通过此方法注册插件 */
install(Vue: App) {
Vue.directive('hasPerm', hasPerm)
Vue.directive('hasRole', hasRole)
}
}
在页面中使用
<a-button
v-hasPerm="['system:btn:add']"
type="primary"
class="con_btn"
:disabled="disabled"
>测试</a-button
>
通过v-hasPerm和v-hasRole可以全局控制控件的权限了,非常方便
好啦,今天大米饭先简单分享一下自定义指令的使用,后续有场景也会多多使用,加油