組件特點
- 自定義文本
- 自定義提醒圖標
- 自定義過渡時間
- 自定義位置
- 顯示隱藏過渡
目錄結構
/toast.vue
<template>
<!-- 一個顯示隱藏過渡 -->
<transition name="fade">
<div class="toastbox" v-if="show" :style="{top:top,left:left}">
<div class="iconbox">
<i :class="icon"></i>
</div>
<div class="textbox">
{{text}}
</div>
</div>
</transition>
</template>
<script>
export default {
};
</script>
<style>
.toastbox{
width: 11em;
height: 11em;
position: absolute;
margin-left: -5.5em;//水平居中:left:50%,margin-left:'自身元素寬度的一半'
border-radius: .4em;
background: rgba(0, 0, 0, 0.8);
position: absolute;
color: white;
}
.iconbox{
display: block;
margin: 1em auto .8em;
text-align: center;
font-size: 2.2em;
}
.textbox{
text-align: center;
}
.fade-enter-active {
transition: all .5s ease;
}
.fade-leave-active {
transition: all .3s ease;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
/index.js
import vue from 'vue'
import toastComponent from './toast.vue'
// 組件構造器,構造出一個vue組件實例
const ToastConstructor = vue.extend(toastComponent)
function showToast ({ text,duration = 3000,icon='el-icon-check',top='30%',left='50%' }) {
const toastDom = new ToastConstructor({
el: document.createElement('div'),
data () {
return {
show: true,// 是否顯示
text: text,// 文本內容
icon: icon,// 圖標
top:top,// 離上方的距離
left:left,// 離左邊的距離
}
}
})
// 添加節點
document.body.appendChild(toastDom.$el)
// 過渡時間:規定多久后隱藏組件
setTimeout(() => {
toastDom.show = false
}, duration)
}
// 全局注冊
function registryToast () {
vue.prototype.$toast = showToast
}
export default registryToast
全局注冊
/mian.js
import toastRegistry from './toast/index'
Vue.use(toastRegistry)
調用
this.$toast({
text: '群組數據保存成功!',
left:'75%',
top:'40%'
})