vue实现点击div外部触发事件的封装方法,注:基于element-ui

链接处:element-ui网址

实现代码

<template>
  <div class="app-container">
    <div v-clickoutside="clickOut" style="background: red">
      我是里面内容
    div>
    <div v-clickoutside="clickOut2" style="background: red">
      我是里面内容2
    div>
  div>
template>

<script>

import Clickoutside from 'element-ui/src/utils/clickoutside'
export default {
  directives: { Clickoutside },
  methods: {
    clickOut() {
      console.log('点击了外面内容')
    },
    clickOut2() {
      console.log('点击了外面内容2')
    }
  }
}

当然也给出clickoutside.js的源码 ( 只会复制粘贴的机器人!!!)

/**
 * v-clickoutside
 * @desc 点击元素外面才会触发的事件
 * @example
 * ```vue
 * 
* ``` */ export default { bind(el, binding, vnode) { nodeList.push(el); const id = seed++; el[ctx] = { id, documentHandler: createDocumentHandler(el, binding, vnode), methodName: binding.expression, bindingFn: binding.value }; }, update(el, binding, vnode) { el[ctx].documentHandler = createDocumentHandler(el, binding, vnode); el[ctx].methodName = binding.expression; el[ctx].bindingFn = binding.value; }, unbind(el) { let len = nodeList.length; for (let i = 0; i < len; i++) { if (nodeList[i][ctx].id === el[ctx].id) { nodeList.splice(i, 1); break; } } delete el[ctx]; } };

你可能感兴趣的:(vue)