在vue中,可以使用vue文件的组件,也可以使用js文件作为组件去调用。使用js组件例如:封装一个消息弹框确认组件,消息提醒组件等等;
vue2
import Vue from 'vue'
// import Vue from 'vue/dist/vue.esm.js'//使用template预编译,则引入此项
export function showMsg() {
return new Promise((resolve, reject) => {
const div = document.createElement('div');
document.body.appendChild(div);
div.setAttribute('id', 'dialog')
new Vue({
// 选项
el: '#dialog', // 通常我们会在这里指定挂载点
data: {
title: '提示',
content: '确定要关闭此页面?'
},
mounted() {
this.$refs.dialogWindow.showModal();
},
render(h) {
return h('dialog', { class: 'dialog-window', ref: "dialogWindow" }, [
h('div', { class: 'dialog-window-title' }, this.title),
h('div', { class: 'dialog-window-content' }, this.content),
h('div', { class: 'dialog-window-button' }, [
h('div', {
class: 'dialog-window-cancel', on: {
click: this.cancelDialog
}
}, '取消'),
h('div', {
class: 'dialog-window-close', on: {
click: this.closeDialog
}
}, '关闭')
])
])
},
methods: {
closeDialog() {
this.$refs.dialogWindow.close();
let body = document.getElementsByTagName('body')[0]
let dialog = document.getElementsByClassName('dialog-window')[0];
body.removeChild(dialog)
resolve()
},
cancelDialog() {
this.$refs.dialogWindow.close();
let body = document.getElementsByTagName('body')[0]
let dialog = document.getElementsByClassName('dialog-window')[0];
body.removeChild(dialog)
reject()
}
}
});
})
}
vue3
import { createApp } from 'vue'
export function messages() {
return new Promise((resolve, reject) => {
const div = document.createElement('div');
document.body.appendChild(div);
div.setAttribute('id', 'dialog')
const app = createApp({
data() {
return {
title: '提示',
content: '确定要关闭此页面?'
}
},
mounted() {
this.$refs.dialogWindow.showModal();
},
render() {
// jsx语法
return (<dialog class="dialog-window" ref="dialogWindow">
<div class="dialog-window-title">{this.title}</div>
<div class="dialog-window-content">{this.content}</div>
<div class="dialog-window-button">
<div class="dialog-window-cancel" onClick={() => this.cancelDialog()}>取消</div>
<div class="dialog-window-close" onClick={() => this.closeDialog()}>关闭</div>
</div>
</dialog>)
},
methods: {
closeDialog() {
app.unmount(div);
div.remove()
resolve()
},
cancelDialog() {
app.unmount(div);
div.remove()
reject()
}
}
});
app.mount(div)
})
}
将此文件引入到main.js或者需要使用的vue文件上,就可以使用
想要在文件在写上css ,可以使用css in js