1 什么情况下需要使用指令?
需要和 DOM elements 交互,就是封装一些小的指令在DOM element上
2 Vue都提供哪些指令形式?
- v-example
- v-example="value" // 传值
- I will show up if stateExample is true
- v-example="'string'" // string 作为表达式传过去
-
- v-example:arg="value" // 传参
-
v-example:arg.modifier="value" //使用modifier
-
3 如何自定义指令?
Vue.directive('tack');
使用
This element has a directive on it
hooks:
- bind: 当指令和element绑定在一起时开始执行
- inserted: 当element 插入到父DOM中开始执行
- update: 当element更新时执行
- componentUpdated: 当element和children更新时执行
- unbind: 当指令被removed时执行
图1 hook解析
el: 指令绑定的element
binding: 包含了传到hook的参数的对象,比如name, value, oldValue, expression, arg 和 modifiers 只读
vnode: 在virtual DOM中可以引用的node,只读
4 示例
- 简单
App.vue
I will now be tacked onto the page
main.js
Vue.directive('tack', { bind(el, binding, vnode) { el.style.position='fixed' }});
- 来个传值的
App.vue
Stick me 70px from the top of the page
main.js
Vue.directive('tack', { bind(el, binding, vnode) { el.style.position = 'fixed' el.style.top = binding.value + 'px' // 使用了binding.value }});
- 试试传参
App.vue
I'll now be offset from the left instead of the top
main.js
Vue.directive('tack', { bind(el, binding, vnode) { el.style.position = 'fixed' const s = (binding.arg === 'left' ? 'left' : 'top') // 判断 binding.arg el.style[s] = binding.value + 'px' }});
- 我想自由地传值
App.vue
Stick me 40px from the top of the page and 100px from the left of the page
main.js
Vue.directive('tack', { bind(el, binding, vnode) { el.style.position = 'fixed' el.style.top = binding.value.top + 'px' // 使用 value.top el.style.left = binding.value.left + 'px' // 使用 value.left }});
参考资料:https://css-tricks.com/power-custom-directives-vue/?utm_source=javascriptweekly&utm_medium=email