第一种方式,使用vue组件的形式结合js文件,前提需要创建一个组件vue文件,还需要创建一个js文件
//MessageBox.vue文件
<template>
<div class="modal">
<div class="box">
<div class="text">{{msg}}</div>
<el-button @click="emit('click')" type="primary">确定</el-button>
</div>
</div>
</template>
<script setup>
const emit = defineEmits(['click'])
defineProps({
msg:{
type:String,
required:true
}
})
</script>
<style scoped>
.modal{
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
z-index: 999;
background-color: #00000050;
display: flex;
justify-content: center;
align-items: center;
}
</style>
// Message.js文件
import {createApp} from 'vue'
import MessageBox from "../components/MessageBox.vue"
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
export function showMsg(msg,onClick){
const div = document.createElement('div');
document.body.appendChild(div)
//渲染组件
const app = createApp(MessageBox,{ //第二个参数就是传递的属性,
msg,
onClick(){
onClick(()=>{
app.unmount();
div.remove()
})
}
});
app.use(ElementPlus)
app.mount(div)
}
使用的,在其他需要使用的vue组件中引入js文件,使用方式如下
<script setup>
import HelloWorld from './components/HelloWorld.vue';
import {showMsg} from "../src/utils/message.js";
function showAlert(){
showMsg('传入的文字',(close)=>{
close()
})
}
</script>
第二种方式是不另外创建vue组件文件,而是直接使用jsx的方式创建组件,利用styled/vue这个库,在js中使用css
import {createApp} from 'vue'
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import styled from "@styled/vue" //CSS-in-JS库,适用于Vue SFC,在Vue单文件组件中使用动态样式
import divModal = styled('div',{ //制作一个带有样式的div
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
z-index: 999;
background-color: #00000050;
display: flex;
justify-content: center;
align-items: center;
})
const MessageBox = {
props:{
msg:{
type:String,
required:true
}
},
render(ctx){
const {$props,$emit} = ctx;
return <DivModal class="modal">
<div class="box">
<div class="text">{$props.msg}</div>
<el-button click={$emit('click')} type="primary">确定</el-button>
</DivModal>
</div>;
}
};
export function showMsg(msg,onClick){
const div = document.createElement('div');
document.body.appendChild(div)
//渲染组件
const app = createApp(MessageBox,{ //第二个参数就是传递的属性,
msg,
onClick(){
onClick(()=>{
app.unmount();
div.remove()
})
}
});
app.use(ElementPlus)
app.mount(div)
}
使用如上