阅读若依前端低代码看见v-permission时去了解vue的directive自定义指令时发现,可注入属性,有点像v-bind的用法。
官方参考文档:https://cn.vuejs.org/guide/reusability/custom-directives.html#introduction
使用vue的webpack模板创建一个项目
# vue init webpack yma16-study
进入目录运行项目
# cd yma16-study
# npm run dev
安装elementui方便使用ui样式验证自定义指令
# npm i element-ui -S
一个自定义指令由一个包含类似组件生命周期钩子的对象来定义
vue2的安装方式
import Vue from 'vue'
// 使 v-focus 在所有组件中都可用
Vue.directive('focus', {/* ... */
})
指令的钩子会传递以下几种参数:
el:指令绑定到的元素。这可以用于直接操作 DOM。
binding:一个对象,包含以下属性。
value:传递给指令的值。例如在 v-my-directive=“1 + 1” 中,值是 2。
oldValue:之前的值,仅在 beforeUpdate 和 updated 中可用。无论值是否更改,它都可用。
arg:传递给指令的参数 (如果有的话)。例如在 v-my-directive:foo 中,参数是 “foo”。
modifiers:一个包含修饰符的对象 (如果有的话)。例如在 v-my-directive.foo.bar 中,修饰符对象是 { foo: true, bar: true }。
instance:使用该指令的组件实例。
dir:指令的定义对象。
vnode:代表绑定元素的底层 VNode。
prevNode:之前的渲染中代表指令所绑定元素的 VNode。仅在 beforeUpdate 和 updated 钩子中可用。
设计v-yma16Auth显示,v-yma16UnAuth不显示
在插入inserted的生命周期触发
const authConfig = {isAuthor: true
}
const unAuthConfig = {isAuthor: false
}
const yma16Auth = {inserted (el, binding, vnode) {const { value } = bindingconsole.log('value', value)console.log('binding', binding)// 未授权 移除节点if (!authConfig.isAuthor) {el.parentNode && el.parentNode.removeChild(el)}}
}
const yma16UnAuth = {inserted (el, binding, vnode) {const { value } = bindingconsole.log('value', value)console.log('binding', binding)// 未授权 移除节点if (!unAuthConfig.isAuthor) {el.parentNode && el.parentNode.removeChild(el)}}
}export {authConfig, yma16Auth, yma16UnAuth, unAuthConfig}
main.js入口
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import {authConfig, yma16Auth, yma16UnAuth, unAuthConfig} from './desing-directive'// 自定义 yma16指令
Vue.directive('yma16Auth', yma16Auth)
Vue.directive('yma16UnAuth', yma16UnAuth)
Vue.prototype.authConfig = authConfig
Vue.prototype.unAuthConfig = unAuthConfigVue.config.productionTip = false
Vue.use(ElementUI)
/* eslint-disable no-new */
new Vue({el: '#app',router,components: { App },template: ' '
})
v-yma16Auth显示,v-yma16UnAuth不显示
binding的值调整显示隐藏
const yma16Auth = {inserted (el, binding, vnode) {const { value } = bindingconsole.log(binding)console.log(el)const {visible} = value// visible false 移除节点if (!visible) {console.log('remove', el)el.parentNode && el.parentNode.removeChild(el)}}
}
视图层
{{ msg }}
重新强制渲染 授权显示的按钮 v-yma16Authv-yma16Auth
隐藏
显示
结束,感谢阅读,如有不足欢迎指出问题!