目录
自定义插件实现
效果演示
代码实现
CSS样式
JavaScript脚本
注册自定义插件
使用自定义插件
Vue3自定义插件的详细教程,点击此处可查看。
.popupWindow {
position: absolute;
top: 5px;
left: calc(50% - 125px); /*水平居中显示*/
/* transform: translateX(-50%); */
/* margin: 5px auto; */
padding: 10px 5px;
display: block;
color: #fff;
width: 250px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: rgba(16, 175, 141, 0.6);
animation-name: fadeup;
animation-duration: 1500ms;
z-index: 999;
}
.information{
background-color: rgba(16, 175, 141, 0.6);
}
.warnning{
background-color: rgba(194, 176, 14, 0.6);
}
.error{
background-color: rgba(235, 70, 20, 0.6);
}
@keyframes fadeup {
0% {
opacity: 0;
-webkit-transform: translate3d(0, 100%, 0);
-moz-transform: translate3d(0, 100%, 0);
transform: translate3d(0, 100%, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
-moz-transform: none;
-o-transform: none;
transform: none;
}
}
import "./index.css";//导入样式文件
export default {
install: (app, options) => {
/**
* 注册一个全局可用的m$messageBox()方法
* @param {*} param options 配置项
* message: 提示信息
* type: 信息类型
* duration: 持续时间
*/
app.config.globalProperties.$messageBox = (
options = {
message: "",
type: "information",
duration: 1500,
}
) => {
console.log(`messageBox`);
const { message = "", type = "information", duration = 1500 } = options; //参数解构
//创建弹框
const popupWidow = document.createElement("div");
if (typeof type === "undefined" || type === null) {
popupWidow.className = "popupWindow";
} else if (type === "information") {
popupWidow.className = "popupWindow information";
} else if (type === "warnning") {
popupWidow.className = "popupWindow warnning";
} else if (type === "error") {
popupWidow.className = "popupWindow error";
}
popupWidow.innerText = message;
document.body.appendChild(popupWidow);
window.requestAnimationFrame(function () {
popupWidow.style.display = "block";
setTimeout(() => {
(function (popupWidow_old) {
document.body.removeChild(popupWidow_old);
})(popupWidow);
}, duration);
});
};
},
};
在main.js文件中进行注册,前提条件:拿到createApp()接口方法创建的app实例,然后调用use()方法进行插件注册。示例代码如下,
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
//导入自定义插件
import MessagePlugin from '@/plugins/MessageBox/MessagePlugin'
//创建Vue-Application实例
const app = createApp(App);
//注册自定义插件
app.use(MessagePlugin);
app.use(store).use(router).mount('#app')
由于自定义插件被挂载到了Vue-Application的全局属性上面,因此, 使用自定义插件时,需要先进行属性解构,拿到$messageBox方法,然后直接调用即可。示例代码如下,