Vue.extend 實現 Dialog 提示組件封裝
在 components 目錄下新建 Dialog 文件夾作為 Dialog 組件文件,新建 index.vue 和 index.js 文件進行組件封裝,並在 main.js 中將組件掛載到 vue 原型上實現全局使用
components/Dialog/index.vue
<template>
<div id="dialog">
<div class="dialog-box">
<p class="title">{{ title }}</p>
<p class="content">{{ content }}</p>
<div class="btn-box">
<button class="left-btn" @click="cancel">{{ left_buttton }}</button>
<button class="right-btn" @click="ok">{{ right_buttton }}</button>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'dialog',
data() {
return {
//顯示標題,默認為“提示”
title: '提示',
//顯示內容
content: '',
//左按鈕顯示文本,默認為“取消”
left_buttton: '取消',
//右按鈕顯示文本,默認為“確定”
right_buttton: '確定'
}
},
methods: {
//點擊取消按鈕
cancel() {
this.onCancel() //點擊取消的回調函數
this.$destroy(true) //銷毀組件
this.$el.parentNode.removeChild(this.$el) //父元素中移除dom元素($el為組件實例)
},
//點擊確定按鈕
ok() {
this.onOk() //點擊確定的回調函數
this.$destroy(true) //銷毀組件
this.$el.parentNode.removeChild(this.$el) //父元素中移除dom元素($el為組件實例)
}
}
}
</script>
<style lang='scss' scoped>
#dialog {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.2);
z-index: 9999;
.dialog-box {
width: 400px;
border-radius: 2px;
background-color: #fff;
position: absolute;
top: 100px;
left: 50%;
transform: translateX(-50%);
padding: 20px 30px;
box-sizing: border-box;
.title {
font-size: 20px;
margin-bottom: 15px;
text-align: center;
}
.content {
font-size: 16px;
line-height: 22px;
}
.btn-box {
width: 100%;
height: 70px;
padding-top: 32px;
padding-left: 170px;
box-sizing: border-box;
button {
width: 65px;
height: 38px;
font-size: 16px;
margin-left: 20px;
border-radius: 2px;
border: none;
outline: none;
cursor: pointer;
}
.left-btn {
background-color: #DCDFE6;
color: #606266;
}
.right-btn {
background-color: #409EFF;
color: #fff;
}
}
}
}
</style>
components/Dialog/index.js:
import Vue from 'vue'
import Dialog from './index.vue'
//創建Dialog構造器
let DialogConstrutor = Vue.extend(Dialog)
let instance
const dialog = function(options = {}) {
//設置默認參數為對象,如果參數為字符串,參數中message屬性等於該參數,回調函數為空
if(typeof options === 'string') {
options = {
content: options,
onOk: () => {},
onCancel: () => {}
}
}
//創建實例
instance = new DialogConstrutor({
data: options
})
//將實例掛載到body下
document.body.appendChild(instance.$mount().$el)
}
export default dialog
main.js
//引入Dialog組件
import Dialog from './components/Dialog'
//將Dialog組件掛載到vue原型上
Vue.prototype.$dialog= Dialog
在需要使用 Dialog 組件的地方調用 this.$dialog) 並傳入參數使用
//傳入對象參數
this.$dialog({
title: '提示',
content: '這是一段提示信息',
left_buttton: '取消',
right_buttton: '確定',
onOk: () => {
console.log('ok');
},
onCancel: () => {
console.log('cancel');
}
})
//傳入字符串參數(該參數會做為參數中content屬性的值,回調函數為空)
this.$dialog('這是一段提示信息')
效果圖

