1. 程式人生 > 其它 >封裝一個的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);

檔案結構

使用

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

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

日子常新,未來不遠