vue3中使用函数调用方式创建自定义组件

第一种方式,使用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)
	
}

使用如上

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值