前言
本文主要介绍弹窗的代码,包括前端、js、css样式,以及点击按钮调用弹窗的过程详解。
步骤如下:
step1 创建一个弹窗
Modal.vue
template
<template> <div class="modal-bg" v-show="show" @mousemove="modalMove" @mouseup="cancelMove"> <div class="modal-container"> <div class="modal-header" @mousedown="setStartingPoint"> {{ title }} </div> <div class="modal-main"> <slot></slot> <p>弹窗里面</p> </div> <div class="modal-footer"> <el-button round @click="cancel">取消</el-button> <el-button type="primary" round @click="submit">确认</el-button> </div> </div> </div> </template>
script
1. <script><script> export default { name: 'Modal', props: { show: { type: Boolean, default: false }, title: { type: String, default: '弹窗' }, }, data() { return { x: 0, y: 0, node: null, isCanMove: false } }, mounted() { this.node = document.querySelector('.modal-container') }, methods: { cancel() { this.$emit('cancel') }, submit() { this.$emit('submit') }, setStartingPoint(e) { this.x = e.clientX - this.node.offsetLeft this.y = e.clientY - this.node.offsetTop this.isCanMove = true }, modalMove(e) { if (this.isCanMove) { this.node.style.left = e.clientX - this.x + 'px' this.node.style.top = e.clientY - this.y + 'px' } }, cancelMove() { this.isCanMove = false } } } </script>
style
<style scoped> .modal-bg { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,.5); z-index: 10; } .modal-container { background: #fff; border-radius: 10px; overflow: hidden; position: fixed; top: 50%; left: 50%; transform: translate(-50%,-50%); } .modal-header { height: 56px; background: #409EFF; color: #fff; display: flex; align-items: center; justify-content: center; cursor: move; } .modal-footer { display: flex; align-items: center; justify-content: center; height: 57px; border-top: 1px solid #ddd; } .modal-footer button { width: 100px; } .modal-main { padding: 15px 40px; } </style>
step2 在router里面引入Modal.vue
1. importimport modal from '../components/Modal'; return[{ path: 'modal', name: '弹窗', component: modal }]
step3 调用
template
<Modal :show="show" @cancel="cancel" @submit="submit"></Modal>
script
import Modal from '../../components/Modal'; export default { data() { return { show: false, } }, components: { Modal }, methods: { cancel() { // 取消弹窗回调 this.show = false }, submit() { // 确认弹窗回调 this.show = false }, showWindow(){ this.show = true }, changeRoute() { this.$router.push('/welcome/page2'); } } };