【java】vue v-for弹出框,怎么实现点击弹出框以外的地方,隐藏弹出框,如下图和代码
问题
点击黑色按钮,弹出框显示
点击弹出框以外的地方,隐藏弹出框
图片
代码,可以直接运行
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<ul>
<li v-for="(item,index) in data1">
<span @click="toggle(index)"></span>
<span>{{item.id}}</span>--
<span>{{item.name}}</span>
<div v-show="(cIndex == index) && dialog">dialog</div>
</li>
</ul>
</div>
<script>
new Vue({
el: '#app',
data: {
dialog:false,
cIndex: -1,
data1: [
{ id: 1, name: "a" },
{ id: 2, name: "b" },
{ id: 3, name: "c" },
{ id: 4, name: "d" },
]
},
methods:{
toggle(index){
this.cIndex = index;
this.dialog = !this.dialog;
}
}
})
</script>
</body>
</html>
<style>
ul,
li {
list-style: none;
}
li {
position: relative;
height: 40px;
line-height: 40px;
border-bottom: 1px solid #000;
}
li span:first-child {
display: inline-block;
width: 10px;
height: 10px;
background-color: #000;
}
li div{
position: absolute;
left: 20px;
top: 0;
z-index: 1000;
width: 100px;
height: 100px;
border: 1px solid red;
background-color: #fff;
}
</style>
回答
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<ul>
<li v-for="(item,index) in data1">
<span @click.stop="toggle(index)"></span>
<span>{{item.id}}</span>--
<span>{{item.name}}</span>
<div v-show="(cIndex == index) && dialog" class="modalDiaLog">dialog</div>
</li>
</ul>
</div>
<script>
new Vue({
el: '#app',
data: {
dialog:false,
cIndex: -1,
data1: [
{ id: 1, name: "a" },
{ id: 2, name: "b" },
{ id: 3, name: "c" },
{ id: 4, name: "d" },
]
},
mounted(){
document.addEventListener('click', (e)=> {
if (e.target.className != 'modalDiaLog') {
this.dialog = false;
}
})
},
methods:{
toggle(index){
this.cIndex = index;
this.dialog = !this.dialog;
}
}
})
</script>
</body>
</html>
<style>
ul,
li {
list-style: none;
}
li {
position: relative;
height: 40px;
line-height: 40px;
border-bottom: 1px solid #000;
}
li span:first-child {
display: inline-block;
width: 10px;
height: 10px;
background-color: #000;
}
li div{
position: absolute;
left: 20px;
top: 0;
z-index: 1000;
width: 100px;
height: 100px;
border: 1px solid red;
background-color: #fff;
}
</style>
弹窗之后, document 监听点击事件 关闭 dialog
document监听点击事件
e.target!=弹窗 的时候,关闭
以上是 【java】vue v-for弹出框,怎么实现点击弹出框以外的地方,隐藏弹出框,如下图和代码 的全部内容, 来源链接: utcz.com/a/73322.html