Vue.directive(指令名,配置对象) 或 Vue.directive(指令名,回调函数) 写在main.js里面
自定义指令中传递的三个参数
el: 指令所绑定的元素,可以用来直接操作DOM。
binding: 一个对象,包含指令的很多信息。
vnode: Vue编译生成的虚拟节点。
自定义指令有五个生命周期(也叫钩子函数),分别是
bind,inserted,update,componentUpdated,unbind
-
bind:只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个绑定时执行一次的初始化动作。
-
inserted:被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于document中)。
-
update:被绑定于元素所在的模板更新时调用,而无论绑定值是否变化。通过比较更新前后的绑定值,可以忽略不必要的模板更新。
-
componentUpdated:被绑定元素所在模板完成一次更新周期时调用。
-
unbind:只调用一次,指令与元素解绑时调用。
案例:
// 局部自定义指令
// showBtn.js
import { checkArray } from '../utils/premissionArray';
export default {
inserted(el, binding) {
console.log('11', binding);
let showBtn = parseInt(binding.value);
if (showBtn) {
let hasPermission = checkArray(showBtn)
// 只有2能进去, let arr = [1, 3, 5] 因为2不存在于这个数组,返回false
if (!hasPermission) {
el.parentNode && el.parentNode.removeChild(el)
}
} else {
throw new Error('error')
}
}
}
// utils/premissionArray.js
export const checkArray = (key) => {
// 权限数组
let arr = [1, 3, 5]
// indexOf查找项目成员的下标,如果没查到,返回 -1
let index = arr.indexOf(key)
console.log(index)
if (index > -1) {
return true
} else {
return false
}
}
<template>
<div class="home">
<button v-show-btn="1">按钮</button>
<button v-show-btn="2">按钮</button>
</div>
</template>
<script>
// @ is an alias to /src
import showBtn from '@/directives/showBtn'
export default {
name: "HomeView",
components: {},
directives: {
showBtn
},
};
</script>