前言
相信大家实际开发中都封装过组件,可能是项目开发中组件使用频繁,或者内容设计有定制需求,这时候就需要封装自定义组件。这里封装一个toast组件,样式随便写的只为实现功能
1. 创建 Toast 组件
创建Toast.vue文件,定义组件 props 参数,代码如下:
<!-- Toast组件 -->
<template>
<div class="toast" v-if="isShow" :style="{width}">
<div v-if="content" class="cont" :style="{ textAlign }">{{ content }}</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed } from "vue";
const props = defineProps({
// 内容
content: {
type: String,
default: "成功"
},
// 显示时间,默认2s
time: {
type: Number,
default: 2000,
},
// 宽度,默认200px,
width: {
default: '200px',
},
// 对齐方式,默认center
textAlign: {
type: String,
default: "center",
},
});
// 弹窗显隐控制
const isShow = ref(false);
// 显示弹窗方法
const show = () => {
isShow.value = true;
if (props.time >= 0) {
setTimeout(() => {
hide()
}, props.time);
}
};
// 隐藏弹窗方法
const hide = () => {
isShow.value = false;
};
// 将显示弹窗方法暴露出去
defineExpose({
show,
});
</script>
<style lang="scss" scoped>
.toast {
position: fixed;
top: 45%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 99;
background: rgb(0,0,0,0.2);
border-radius: 3px;
padding: 20px;
text-align: center;
box-shadow: 0px 0px 2px #f1f1f1;
.cont{
font-size: 14px;
color: #fff;
line-height: 20px;
}
}
</style>
2. 创建实例
vue3 用 createApp 创建 Vue 应用实例
import { createApp } from "vue";
import Toast from '../components/Toast/index.vue';
let toastDom = null;
let app = null;
const xToast = options => {
const dom = document.body.querySelector('.my-toast');
// toast元素是否存在
if (!dom) {
// 创建元素节点
toastDom = document.createElement("div");
// 给元素设置class
toastDom.className = `my-toast`;
// 在body标签内部插入此元素
document.body.appendChild(toastDom);
} else {
app.unmount();
}
// 创建应用实例(第一个参数是根组件。第二个参数可选,它是要传递给根组件的 props)
app = createApp(Toast, {
...options,
hide () {
if (app) {
// 卸载实例
app.unmount();
app = null;
}
if (toastDom) {
// 删除dom
document.body.removeChild(toastDom);
toastDom = null;
}
},
});
// 将实例挂载到创建的 DOM 元素上
return app.mount(toastDom);
};
// toast显示
xToast.show = options => xToast(options).show();
export default xToast;
3. 调用
没弄全局方法,需要可自加
// 导入组件
import Toast from "@/plugs/toast";
// 调用toast,{参数对应props}
Toast.show({content:'测试数据'})
如果此篇文章对您有帮助,欢迎您【点赞】、【收藏】!也欢迎您【评论】留下宝贵意见,共同探讨一起学习~