當然军洼,要想實現(xiàn)這種效果锤窑,方法有很多关面。
- 通過定義組件坦袍,先在
App.vue
里面放置,并通過改變?nèi)肿兞窟M行控制- 通過
Vue.extend
創(chuàng)建構造器缭裆,手動把組件掛載到DOM上去
這里只是簡單告訴了你們?nèi)绾问褂眉耄喙δ芸梢愿鶕?jù)需求自己定義
????
Toast組件目錄
這篇文章主要是通過
Vue.extend
的方法
main.js中引入
import Toast from './components/Toast'
Vue.prototype.$toast = Toast //掛載到vue原型上
main.vue
<template>
<transition name="fade">
<div id="toast" v-if="visible">
<div class="toast">{{message}}</div>
</div>
</transition>
</template>
<script>
export default {
watch: {
closed(val) {
if (val) {
this.visible = false;
// this.destroyElement();
}
}
},
data() {
return {
visible: false,
message: "",
duration: 3, // 顯示時長,秒
closed: false, // 用來判斷消息框是否關閉
timer: null // 計時器
};
},
mounted() {
this.startTimer();
},
methods: {
//完全銷毀實例
destroyElement() {
// https://cn.vuejs.org/v2/api/#vm-destroy
this.$destroy();
this.$el.parentNode.removeChild(this.$el);
},
//計時器澈驼,根據(jù) duration 去修改組件的開關狀態(tài)
startTimer() {
this.timer = setTimeout(() => {
if (!this.closed) {
this.closed = true;
clearTimeout(this.timer);
}
}, this.duration * 1000);
}
}
};
</script>
<style lang="scss" scoped>
#toast {
z-index: 9999;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
.toast {
display: inline-block;
max-width: 80vw;
background: rgba(24, 151, 119, 0.63);
padding: 0.5rem 1rem;
text-align: center;
color: white;
font-size: 14px;
}
}
.fade-enter-active {
animation: fade 1s;
}
.fade-leave-active {
animation: fade 1s reverse;
}
@keyframes fade {
0% {
transform: scale(1) translateX(200px);
opacity: 0;
}
100% {
transform: scale(1) translateX(0);
opacity: 1;
}
}
</style>
index.js
import Vue from 'vue';
import Main from './main.vue'
// https://cn.vuejs.org/v2/api/#Vue-extend
// 創(chuàng)建構造器
let ToastConstructor = Vue.extend(Main);
let instance
let seed = 1 // 計數(shù)
const Toast = (options = {}) => {
//判斷如果傳入的是一個字符串辛燥,那么就使用message提示
if (typeof options === 'string') {
options = {
message: options
}
}
let id = `toast_${seed++}`
instance = new ToastConstructor({
data: options
})// 創(chuàng)建對象實例
instance.id = id
// https://cn.vuejs.org/v2/api/#vm-mount
// 手動掛載一個實例并插入到 body 中
instance.$mount()
document.body.appendChild(instance.$el)
instance.visible = true
return instance
}
export default Toast
使用
this.$toast("我是一個Toast輕提示");
or
this.$toast({ message: "我是一個Toast輕提示", duration: 2 });