先看Modal.vue代码
<template>
<div draggable="true" class="modal" v-bind:style="{ 'width':width, 'height':height, 'display':none }">
<div class="modal-header">
<span>{{ title }}</span>
<span><a href='#' @click='hide()'>[隐藏]</a><a href='#' v-on:click='close()'>[关闭]</a></span>
</div>
<div class="modal-content">
{{{ content }}}
</div>
</div>
</template>
<script>
export default {
props: {
width: String,
height: String,
title: String,
isAutoClose: Boolean,
isModal: Boolean,
isShow: Boolean
},
ready () {
let _$el = this.$el
let mouseX = 0
let mouseY = 0
// 居中计算
let w = parseInt(this.width)
let h = parseInt(this.height)
this.$el.style.top = (window.innerHeight - h) / 2 + 'px'
this.$el.style.left = (window.innerWidth - w) / 2 + 'px'
let moveFlag = false
let header = this.$el.querySelector('.modal-header')
header.onmousedown = function (e) {
moveFlag = true
mouseX = e.clientX
mouseY = e.clientY
}
header.onmousemove = function (e) {
}
header.onmouseout = function (e) {
if (moveFlag) {
let t = parseFloat(_$el.style.top)
let l = parseFloat(_$el.style.left)
_$el.style.top = (t + (e.clientY - mouseY)) + 'px'
_$el.style.left = (l + (e.clientX - mouseX)) + 'px'
moveFlag = false
}
}
},
methods: {
close: function () {
this.$el.remove()
// 分发关闭(close)事件
this.$dispatch('close')
},
show: function () {
this.$el.style.display = 'block'
},
hide: function () {
this.$el.style.display = 'none'
}
},
data () {
return {}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.modal{
min-width: 120px;
min-height: 100px;
box-shadow: 3px 3px 5px #333333;
position: fixed;
z-index: 9999;
background: #42B983;
display: flex;
flex-flow: column nowrap;
}
.modal .modal-header{
line-height: 40px;
height: 40px;
border-bottom: 1px solid #FFFFFF;
color: #FFFFFF;
display: flex;
justify-content: space-between;
}
.modal .modal-header:hover{
cursor: move;
}
.modal .modal-header > span{
margin-right: 10px;
margin-left: 10px;
}
.modal .modal-header a{
color:#FFFFFF;
text-decoration: none;
}
.modal-content{
height: 100%;
}
</style>
Modal的实例图:
然后再父组件需要调用的地方引入:
import Vue from 'vue'
import Modal from './components/Modal'
然后再需要创建的地方执行试下代码、可以循环创建
let ModalComponent = Vue.component('modal', Modal)
// 实例化组件
let _modal = new ModalComponent({
data: function () {
return {
width: '400px',
height: '300px',
title: param.name,
content: param.src || param.html
}
}
})
_modal.$mount().$appendTo('body')
效果图: