vue 3 手写原生弹出框
时间: 2024-05-26 18:09:12 浏览: 14
Vue 3 是一款流行的 JavaScript 框架,用于构建用户界面和单页面应用程序。手写原生弹出框可以通过 Vue 3 的组件来实现,以下是一个简单的示例:
1. 新建一个名为 "MyAlert" 的 Vue 组件,该组件包含一个 "message" 属性和一个方法 "closeAlert"。
```
<template>
<div class="my-alert" v-show="visible">
<div class="my-alert-mask" @click="closeAlert"></div>
<div class="my-alert-content">
<p>{{ message }}</p>
<button @click="closeAlert">确定</button>
</div>
</div>
</template>
<script>
export default {
props: {
message: {
type: String,
default: "",
},
},
data() {
return {
visible: true,
};
},
methods: {
closeAlert() {
this.visible = false;
},
},
};
</script>
<style scoped>
.my-alert {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.my-alert-mask {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
}
.my-alert-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
}
</style>
```
2. 在需要弹出框的地方使用该组件,并传递要显示的消息。
```
<template>
<div>
<button @click="showAlert">弹出框</button>
<my-alert :message="alertMsg" v-if="isShowAlert" @closeAlert="isShowAlert=false"></my-alert>
</div>
</template>
<script>
import MyAlert from "./MyAlert.vue";
export default {
components: {
MyAlert,
},
data() {
return {
isShowAlert: false,
alertMsg: "",
};
},
methods: {
showAlert() {
this.isShowAlert = true;
this.alertMsg = "这是一个弹出框";
},
},
};
</script>
```
这样就可以实现一个简单的手写原生弹出框。相比于使用浏览器的原生弹出框,自定义的弹出框更加灵活,并且可以根据需求进行自由扩展。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)