Vue自定义指令写法与个人理解

2020-06-13 10:34:50易采站长站整理

unbind: 一旦指令被移除时触发

就个人而言, bind和update也许是这五个里面最有用的两个钩子了.
每个钩子都有el, binding, 和vnode参数可用. update和componentUpdated钩子还暴露了oldVnode, 以区分传递的旧值和较新的值.

el, 跟你所期待的一样, 就是所绑定的元素. binding是一个保护传入钩子的参数的对象. 有很多可用的参数, 包括name, value, oldValue, expression, arguments, arg及修饰语. vnode有一个更不寻常的用例, 它可用于你需要直接引用到虚拟DOM中的节点. binding和vnode都应该被视为只读.

绑定一个自定义指令

既然我们已经知道了这一点, 就可以开始研究如何在实际中使用一个自定义指令. 让我们完善刚才所创建的第一个指令, 让它变得有用:


Vue.directive('tack', {
bind(el, binding, vnode) {
el.style.position = 'fixed'
}
});

在HTML元素中:


<p v-tack>I will now be tacked onto the page</p>

毫无疑问, 它完全可以按照我们所希望的工作. 但是它还不够灵活, 如果我们可以传入一个值, 然后直接更新或者重用这个指令就好了. 例如, 我们想为这个元素指定一个值, 表示这个元素离顶部多远(多少个像素), 我们可以这样写(在CODEPEN上查看):


// JS
Vue.directive('tack', {
bind(el, binding, vnode){
el.style.position = 'fixed';
el.style.top = binding.value + 'px';
}
});

// HTML
<div id="app">
<p>Scroll down the page</p>
<p v-tack="70">Stick me 70px from the top of the page</p>
</div>

假设我们想要区分从顶部或者左侧偏移70px, 我们可以通过传递一个参数来做到这一点(在CODEPEN上查看):


// JS
Vue.directive('tack', {
bind(el, binding, vnode) {
el.style.position = 'fixed';
const s = (binding.arg === 'left' ? 'left' : 'top');
el.style[s] = binding.value + 'px';
}
});

// HTML
<p v-tack:left="70">I'll now be offset from the left instead of the top</p>

当然, 你可以同时传入不止一个值. 你可以像使用标准指令一样简单的使用自定义指令(在CODEPEN上查看):


// JS
Vue.directive('tack', {
bind(el, binding, vnode) {
el.style.position = 'fixed';
el.style.top = binding.value.top + 'px';
el.style.left = binding.value.left + 'px';
}
});

// HTML
<p v-tack="{top: '40', left: '100'}">Stick me 40px from the top of the page and 100px from the left of the page</p>

基于我们的自定义指令, 我们可以创建和修改方法, 从而创建更为复杂的自定义指令. 这里, 我们将做一个waypoints-like例子, 用少量的代码实现特定滚动事件触发的动画效果(在CODEPEN上查看):