自定义v-show功能

  1. // stealth.js
  2. // 元素隐藏显示指令
  3. export default {
  4. // 只调用一次,指令第一次绑定到元素时调用
  5. bind (el, binding, vnode) {
  6. el.style.display = binding.value ? 'block' : 'none'
  7. },
  8. // 被绑定元素插入父节点时调用
  9. inserted (el, binding, vnode) {
  10. console.log('inserted')
  11. },
  12. // 所在组件的 VNode 更新时调用
  13. update (el, binding, vnode) {
  14. console.log('update')
  15. el.style.display = binding.value ? 'block' : 'none'
  16. },
  17. // 指令所在组件的 VNode 及其子 VNode 全部更新后调用
  18. componentUpdated (el, binding, vnode) {
  19. console.log('componentUpdated')
  20. },
  21. unbind (el, binding, vnode) {
  22. console.log('unbind')
  23. }
  24. }
  1. // directives.js
  2. import stealth from './modules/stealth'
  3. export {stealth}
  1. // main.js
  2. import * as directives from './directives'
  3. // 注册指令
  4. Object.keys(directives).forEach(k => Vue.directive(k, directives[k]))
  1. <div v-stealth="true"></div>