封装一个的toast弹出框(vue项目)

  • A+
所属分类:Web前端
摘要

逆风的方向,更适合飞翔   注意的点:toast消失后记得销毁vue实例,清空定时器,移除dom元素

封装一个的toast弹出框(vue项目)

逆风的方向,更适合飞翔

实现效果

封装一个的toast弹出框(vue项目)

 

 

 实现步骤

先写出一个toast组件

// Toast.vue <template> <div id="toast" :class="[isActive ? 'active' : '', type]"> {{ message }} </div> </template>  <script> export default { name: "Toast", data() { return { message: "",//传递的消息 isActive: false,//是否处于活跃状态(显示在页面内) type: "",//消息样式 timer1: null, timer2: null, }; }, mounted() { this.$nextTick(() => { this.isActive = true; }); this.timer1 = setTimeout(() => { this.isActive = false; }, this.delayer); this.timer2 = setTimeout(() => { this.$destroy(true);//销毁vue实例 }, this.delayer * 2); }, destroyed() { this.$el.parentNode.removeChild(this.$el);//移除dom元素 clearTimeout(this.timer1); clearTimeout(this.timer2); }, }; </script>  <style scoped> #toast { position: fixed; top: -50px; left: 50%; transform: translate(-50%, 0); padding: 13px 20px; border-radius: 15px; z-index: 999; opacity: 0; transition: all 1s; } #toast.success { background-color: #f0f9eb; color: #67c23a; } #toast.error { background-color: #fef0f0; color: #f56c6c; } #toast.active { top: 30px; opacity: 1; } </style>

 注意的点:toast消失后记得销毁vue实例,清空定时器,移除dom元素

封装成一个插件

// index.js import Toast from "./Toast.vue"; const obj = {}; obj.install = function(Vue) {  //1. 创建组件构造器 const toastContrustor = Vue.extend(Toast);  Vue.prototype.$toast = function(message, type, delayer = 3000) {  //2. new的方式,根据组件构造器,可以创建出来一个组件对象 const toast = new toastContrustor();  Object.assign(toast, { message, type, delayer });  //3. 将组件对象手动的挂载到一个元素上面  toast.$mount(document.createElement("div"));  //4. toast.$el对应的就是div document.body.appendChild(toast.$el); }; };  export default obj;

 

//main.js import toast from "components/common/toast";  Vue.use(toast);

 

文件结构

封装一个的toast弹出框(vue项目)

 

使用

this.$toast("hi,i am spiderman", "success", 5000);  this.$toast("hi,i am spiderman", "error", 5000);

日子常新,未来不远