Vue自定义指令v-click-outside,及指令生命周期用法bind、unbind;el.contains()方法(摘录)

  • Post author:
  • Post category:vue


<template>
  <div v-click-outside>//自定义指令名称:v-click-outside
    <input type="text" :value="formatDate">
    <div v-if="isVisibale">
      内容
    </div>
  </div>
</template>

<script>
import * as utils from '@/util'
export default {
  name: 'DataPicker',
  data () {
    return {
      isVisibale: false
    }
  },
  directives: {
    clickOutside: {//自定义指令:clickOutside
      bind (el, bindings, vnode) {//自定义指令生命周期:bind ;参数:el, bindings, vnode
        let handler = (e) => {
          if (el.contains(e.target)) {
            if (!vnode.context.isVisibale) {
              vnode.context.focus()
            }
          } else {
            if (vnode.context.isVisibale) {
              vnode.context.blur()
            }
          }
        }
        el.handler = handler
        document.addEventListener('click', handler)
      },
      unbind (el) {//自定义指令生命周期:unbind 
        document.removeEventListener('click', el.handler)
      }
    }
  },
  props: {
    value: {
      type: Date,
      default: () => new Date()
    }
  },
  computed: {
    formatDate () {
      let {year, month, day} = utils.getYearMonthDay(this.value)
      return `${year}-${month}-${day}`
    }
  },
  methods: {
    focus () {
      this.isVisibale = true
    },
    blur () {
      this.isVisibale = false
    }
  }
}
</script>

更多请看视屏,原文25~30分钟处

从零实现Vue高级日历组件