指令注册只能全局指令和选项式页面指令,composition api没有页面指令
选项式页面指令
javascript"><template><div class="home"><h3>自定义指令</h3><div class="from"><el-input type="text" v-focus v-model="name" /></div></div>
</template>
<script>export default {data() {return {name: ''}},directives: {focus: {mounted(el, binding, vnode) {// el代表DOM实例// binding获取到传入的参数及验证v-focus.a.b.c的修饰符,获取其中的a、b、c// vnode获取当前的虚拟DOMconsole.log('el', el, binding, vnode);console.log('el.style',el.style);el.style.border = '1px solid red'el.focus()}}}}
</script>
<style lang="scss" scoped>
.home{display: flex;// justify-content: center;flex-direction: column;align-items: center;
}
.from{width: 20%;
}
</style>
全局指令
javascript">// main.js
import {createApp} from 'vue'
import App from './App'
// 引入指令文件
import hasPermi from './directive/hasPermi'
const app = createApp(App)
// 注册指令
app.directive('hasPermi', hasPermi)
app.mount('#app')
模拟按钮权限
javascript">// /api/role.js
/*** todo: 模拟权限按钮*/
// 数据操作返回的接口返回值
export const roleUser = ['user:admin:update', 'user:admin:delete', 'user:admin:add', 'user:admin:search', 'user:admin:list'
]
javascript">// /directive/hasPermi
// 获取根据用户获取用户按钮权限
import { roleUser } from '@/api/role';
// 按钮权限
export default {mounted(el, binding, vnode) {const { value } = bindingconst all_permission = "*:*:*";// 后端返回的角色按钮权限const permissions = roleUserif (value && value instanceof Array && value.length > 0) {// 前端定义的const permissionFlag = valueconst hasPermissions = permissions.some(permission => {return all_permission === permission || permissionFlag.includes(permission)})console.log('hasPermissions', hasPermissions);if (!hasPermissions) {el.parentNode && el.parentNode.removeChild(el)}} else {throw new Error(`请设置操作权限标签值`)}}
}
页面使用
javascript"><template><div class="home"><div :style="{color: nowColor }">当前颜色:{{ nowColor }}</div><div class="event"><el-button class="bg-lime-500" type="success" @click="alterColor">改变颜色</el-button></div><hr /><div class="directives"><h2>自定义显示按钮</h2><!-- 该用户没权限,所以不显示 --><el-button v-hasPermi="['user:admin:detail']">详情</el-button></div></div>
</template>