js调用modal组件
JS部分
// msgbox/index.js
import Vue from 'vue'
import msgboxVue from './msgbox'
var instance
const MsgBoxConstructor = Vue.extend(msgboxVue)
var initInstance = function() {
instance = new MsgBoxConstructor({
name: 'msgbox',
el: document.createElement('div')
})
}
var showMsgBox = function() {
document.body.appendChild(instance.$el)
Vue.nextTick(() => {
instance.show = true
})
}
var MsgBox = function(options) {
if (!instance) {
initInstance()
}
if (typeof options === 'string') {
instance.content = options
} else {
Object.assign(instance, options)
if (instance.contentEl) {
instance.content = instance.contentEl.innerHTML
}
}
showMsgBox()
}
export default MsgBox
组件部分
// msgbox/msgbox.vue
<template>
<transition name="msgbox-bounce">
<div class="msgbox-wrapper" v-show="show">
<div class="msgbox" :class="msgboxClass">
<div class="msgbox-header" v-show="title" v-html="title"></div>
<div class="msgbox-body" v-html="content"></div>
<div class="msgbox-footer">
<a href="javascript:;" @click="handleAction('ok')">{{buttonText}}</a>
</div>
</div>
<div class="msgbox-mask" @click="handleAction('close')"></div>
</div>
</transition>
</template>
<script>
export default {
data() {
return {
show: false,
scrollTop: 0
}
},
props: {
title: String,
content: String,
msgboxClass: String,
buttonText: {
type: String,
default: '确定'
}
},
watch: {
show(val) {
if (val) {
this.onShow && this.onShow()
this.scrollTop = document.body.scrollTop
document.body.classList.add('fixed-body')
document.body.style.top = -this.scrollTop + 'px'
} else {
document.body.classList.remove('fixed-body')
document.body.scrollTop = this.scrollTop
}
}
},
methods: {
handleAction(action) {
if (action === 'ok') {
this.show = false
this.onOk && this.onOk()
} else if (action === 'close') {
this.show = false
this.onClose && this.onClose()
}
}
}
}
</script>
调用组件
// home.vue
import MsgBox from 'components/msgbox'
MsgBox({
content: '你尚未开通此功能',
buttonText: "关闭"
})
Last updated