一、想实现给整个页面添加蒙层功能
- 原始代码如下:实现了点击按钮加一个蒙层,蒙层覆盖在绿色背景区域上
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>30</title>
<style>
.area {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 300px;
background: green;
}
.mask {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background: #000;
opacity: 0.5;
}
</style>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
<script>
// teleport 传送门
const app = Vue.createApp({
data() {
return {
show: false
}
},
methods: {
handleBtnClick() {
this.show = !this.show;
}
},
template: `
<div class="area">
<button @click="handleBtnClick">按钮</button>
<div class="mask" v-show="show"></div>
</div>
`
});
app.directive('pos', (el, binding) => {
el.style.top = (binding.value + 'px')
})
app.directive('pos', {
mounted(el, binding) {
el.style.top = (binding.value + 'px')
},
updated(el, binding) {
el.style.top = (binding.value + 'px');
}
})
const vm = app.mount('#root')
</script>
</body>
</html>
如上代码存在的问题:蒙层只覆盖到绿色背景区域,理想情况是覆盖到全部页面,如果覆盖全部页面,则需要将蒙层加到body上
2. 通过传送门标签,将蒙层传送到body标签中(to的值是要传送到的标签)
<teleport to="body">
<div class="mask" v-show="show"></div>
</teleport>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>30</title>
<style>
.area {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 300px;
background: green;
}
.mask {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background: #000;
opacity: 0.5;
}
</style>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
<script>
// teleport 传送门
const app = Vue.createApp({
data() {
return {
show: false
}
},
methods: {
handleBtnClick() {
this.show = !this.show;
}
},
template: `
<div class="area">
<button @click="handleBtnClick">按钮</button>
<teleport to="body">
<div class="mask" v-show="show"></div>
</teleport>
</div>
`
});
app.directive('pos', (el, binding) => {
el.style.top = (binding.value + 'px')
})
app.directive('pos', {
mounted(el, binding) {
el.style.top = (binding.value + 'px')
},
updated(el, binding) {
el.style.top = (binding.value + 'px');
}
})
const vm = app.mount('#root')
</script>
</body>
</html>
如果指定传送到标签的id,则写法如下:
<teleport to="#hello">
<div class="mask" v-show="show"></div>
</teleport>