Vue全域性彈窗

今天來搞一個全域性彈窗,不用每個檔案都引入,只在main.js裡作為全域性原型引入就好了

先新建彈窗元件

toast.vue

<template></template>

<script>
export default {
toast(text) {
this.text = text;
var dom = document.createElement("toast");//Vue不支援直接使用appendChild方法向dom中新增元素,所以需要用到這個奇怪的方法,來建立一個dom節點
dom.className = "toast"; //給我們建立的dom節點寫一個類名
dom.id = "toast" //這是id
dom.innerHTML = text; //這個就是內容了,我們把引數 text 傳入到這裡
document.getElementById("app").appendChild(dom); //現在我們可以拿著做好的節點 直搗黃龍,插入到我們想要插入的地方了
setTimeout("document.getElementById('toast').remove()", 3000 ) //事情辦完之後,就要拔出來,別問我為什麼只有三秒
},
data() {
return {
text: "",
};
},
};
</script> <style>
</style>

這樣,我們建立好了一個

{{text}}

這樣的標籤。

這時我們需要把樣式寫到index.html裡,使它全域性生效。

index.html

//index.html
.toast {
position: fixed;
font-size: 14px;
color: #888;
top: 20px;
background: #fff;
box-shadow: 0 0 10px #52525278;
height: 20px;
z-index: 99999999;
text-align: center;
border-radius: 10px;
padding: 25px 130px;
animation: toast 3s forwards cubic-bezier(0.57, 0.85, 0.85, 0.57);
}
//因為我們設定3秒後銷燬元素,所以動畫要控制在3秒以內
//加點小動畫
//index.html @keyframes toast {
1% {
opacity: 0;
right: -200px;
}
10%{
opacity: 1;
right: 20px;
}
90%{
opacity: 1;
right: 20px;
}
100% {
opacity: 0;
right: -200px;
display: none;
}
}

好了,萬事俱備,只欠東風了,我們在main.js中註冊它

main.js

import toast from './toast'
Vue.prototype.$toast = toast
//我們像使用npm下載的外掛一樣,直接將它註冊為全域性prototype
//現在我們就可以在Vue專案中的任何一個地方喚醒它了
//小傢伙總是出現在右上角!
this.$toast.toast("ok");
//在引號中傳入你想展示的文字吧

它出現了