vue 自定义指令篇
对于vue的指令,有咱们熟悉的v-model、v-show等,但咱们也能够本身定义咱们须要的指令,如比较经常使用的v-lazy懒加载
官方详细文档:https://cn.vuejs.org/v2/guide...
经过directive就能够在Vue上注册指令html
// 注册一个全局自定义指令 `v-focus` Vue.directive('focus', { // 当被绑定的元素插入到 DOM 中时…… inserted: function (el) { // 聚焦元素 el.focus() } })
一个指令定义对象能够提供以下几个钩子函数 (均为可选):vue
bind:只调用一次,指令第一次绑定到元素时调用。在这里能够进行一次性的初始化设置。node
inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不必定已被插入文档中)。git
update:所在组件的 VNode 更新时调用,可是可能发生在其子 VNode 更新以前。指令的值可能发生了改变,也可能没有。可是你能够经过比较更新先后的值来忽略没必要要的模板更新 (详细的钩子函数参数见下)。github
componentUpdated:指令所在组件的 VNode 及其子 VNode 所有更新后调用。ide
unbind:只调用一次,指令与元素解绑时调用。模块化
指令模块化
好比咱们熟悉的v-show,不看源码,咱们分析v-show这个指令的功能,v-show="true || false"显示或者所以节点,但元素不占据其原本的空间。所以这能够经过咱们经常使用的display="none"同样
咱们的想法是注册一个指令,经过给钩子函数传递参数true 或 false去改变节点的display的值函数
stealth.jsui
// 元素隐藏显示指令 export default { // 只调用一次,指令第一次绑定到元素时调用 bind (el, binding, vnode) { el.style.display = binding.value ? 'block' : 'none' }, // 被绑定元素插入父节点时调用 inserted (el, binding, vnode) { console.log('inserted') }, // 所在组件的 VNode 更新时调用 update (el, binding, vnode) { console.log('update') el.style.display = binding.value ? 'block' : 'none' }, // 指令所在组件的 VNode 及其子 VNode 所有更新后调用 componentUpdated (el, binding, vnode) { console.log('componentUpdated') }, unbind (el, binding, vnode) { console.log('unbind') } }
指令模块化,经过index.js管理自定义指令。添加新指令只需在modules中加入模块,并引入
index.jsspa
import stealth from './modules/stealth' export {stealth}
全局Vue中经过directive绑定所有指令
mian.js
import * as directives from './directives' // 注册指令 Object.keys(directives).forEach(k => Vue.directive(k, directives[k]))
业务组件中,加入v-*(指令名)
<div v-stealth="true"></div>
咱们成功完成自定义指令的模块化
完整项目github地址:https://github.com/hty7/vue-demo