鍍金池/ 問答/HTML/ vue點(diǎn)擊頁面任意位置讓子組件消失

vue點(diǎn)擊頁面任意位置讓子組件消失

我記得用原生js是document.body.onclick = function(){} 用vue在根div加了一個(gè)點(diǎn)擊事件 試了一下也能消失 但是不知道這種方法正規(guī)嗎?不知道還有其他的辦法嗎

<template>
 <div @click="none">
      <div id="drop-down">
        <Dropdown v-if="dd"></Dropdown>
      </div>
 </div>
</template>
export default {
  name: 'Blog',
  data () {
    return {
      dd: true
    }
  },
  methods: {
    none () {
      this.dd = false
    }
  },
回答
編輯回答
扯機(jī)薄

建議放到組件里面,比較方便代碼復(fù)用。

beforeMount() {
  this._close = e => {
    // 如果點(diǎn)擊發(fā)生在當(dāng)前組件內(nèi)部,則不處理
    if (this.$el.contains(e.target)) {
      return;
    }
    this.$emit('hide');
  };  
  document.body.addEventListener('click', this._close);
},
beforeDestroy() {
  document.body.removeEventListener('click', this._close);  
}
2017年12月13日 11:17