vue點選空白處隱藏
阿新 • • 發佈:2018-11-19
提供兩種常用方法
1、方法比較簡單,原理是需要隱藏的點選document使其show的值為false,
點選需要出現的加上阻止冒泡即可。@click.stop="isShow"
mounted(){ var that=this;//this的指向問題 document.addEventListener('click',function(e){ that.show=false; //這裡that代表元件,this代表document }) }, methods{ isShow:function(){ this.show=true } }
2、將點選的區域過濾。不需要再阻止冒泡,需要使用到ref屬性
<template> <div ref="box"> <div @click="isShow"></div> </div> </template> mounted(){ let that=this; document.addEventListener('click',function(e){ if(!that.$refs.box.contains(e.target)){ that.show = false; } }) }, methods:{ isShow:function(){ this.show=true } }