弹窗练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>插槽</title>
//写弹窗的样式
<style>
*{
margin:0;
padding:0;
}
.mask{
position:fixed;
width:100%;
height:100%;
left:0;
top:0;
background-color:rgba(0,0,0,.35);
}
.mask .show{
position: absolute;
left:0;
right:0;
top:0;
bottom: 0;
width:600px;
height:350px;
margin:auto;
background: #fff;
}
.mask .show button{
position: absolute;
right:0;
}
</style>
</head>
<body>
//定义一个父子件
<div id="app" >
<button @click="fn">点击弹窗</button>
<hide v-if="isShow" @xxx="close"></hide>//用isshow来判断是否显示弹窗的样式
</div>
//定义一个子组件
<template id="hide">
<div class="mask">
<div class="show">
<button @click="fn">关闭弹窗</button>
</div>
</div>
</template>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
let hide = {
template:'#hide',
methods:{
fn(){ //向父组件发射xxx事件
this.$emit('xxx')
}
}
}
let vm = new Vue({
el:'#app',
data:{
isShow:false, //控制弹窗显示
},
components:{
hide
},
methods:{
fn(){
this.isShow = true;
},
close(){
this.isShow = false;
}
}
})
</script>
</body>
</html>
eventBus
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin:0;
padding:0;
}
.mask{
position:fixed;
width:100%;
height:100%;
left:0;
top:0;
background-color:rgba(0,0,0,.35);
}
.mask .show{
position: absolute;
left:0;
right:0;
top:0;
bottom: 0;
width:600px;
height:350px;
margin:auto;
background: #fff;
}
.mask .show button{
position: absolute;
right:0;
}
</style>
</head>
<body>
<div id="app" >
<heaven></heaven>
<xiaoming></xiaoming>
</div>
<template id="heaven">
<div @click="fn"> {{msg}}</div>
</template>
<template id="xiaoming">
<div @click="fn"> {{msg}} </div>
</template>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
let eventBus = new Vue();//相当于设置一个全局的组件
let heaven = {
template:'#heaven',
data(){
return {
msg:'我是heaven'
}
},
created(){
eventBus.$on('xxx',(msg)=>{ //heaven组件先订阅一个事件
console.log('xxx事件已经触发了 我监控到了',msg)
});
},
methods:{
fn(){
eventBus.$emit('yyy',this.msg)
}
}
}
let xiaoming = {
template:'#xiaoming',
data(){
return {
msg:'我是xiaoming'
}
},
created(){
eventBus.$on('yyy',(msg)=>{
console.log('yyy事件已经触发了 我监控到了',msg)
});
},
methods:{
fn(){
eventBus.$emit('xxx',this.msg)
}
}
}
let vm = new Vue({
el:'#app',
components:{
heaven,
xiaoming
}
})
</script>
</body>
</html>