前言
對於之前封裝的loading組件想要進行一個優化,然後想到可以不用在頁面中添加template引入組件模板,而是直接將組件掛載到vue實例上,使用this原型調用組件並傳值
需求
需要一個全局倒計時loading框,倒計時可自定義,提示信息可自定義
實現
組件內容
loading.vue
<template>
<section v-if="show">
<div class='mock'>
<div class='dot-div'>
<div class="dot dot-one"></div>
<div class="dot dot-two"></div>
<div class="dot dot-three"></div>
<div class="dot dot-four"></div>
</div>
<div class="wrapp">
<div class="
loading-text">
{{message}}
</div>
<div class="time-text">
<span class="tome-countdown">{{count}}</span>
<span class="sec">s</span>後回到首頁
</div>
</div>
</div>
</section>
</template>
<script type="text/babel">
export default {
data () {
return {
count: 0,
timer: null,
show: true,
message: '',
};
},
methods: {
/**
* 開啓倒計時
*/
startTimer () {
if (this.count > 0) {
this.timer = setTimeout(() => {
this.startTimer();
this.count -= 1;
}, 1000);
} else {
clearTimeout(this.timer);
this.timer = null;
this.show = false;
}
},
/**
* 清除計時器
*/
clearTimer () {
clearTimeout(this.timer);
},
/**
* 關閉倒計時
*/
hide () {
this.count = 0;
this.show = false;
this.clearTimer();
}
},
mounted () {
this.startTimer();//開啓倒計時
},
};
</script>
封裝組件實例
loading.js
import Vue from 'vue'
import Main from './loading.vue'
const loadingConstructor = Vue.extend(Main)
let instance;
const loading = function (options) {
if (Vue.prototype.$isServer) return;
//組件實例化
instance = new loadingConstructor({
data: options
})
//組件掛載
instance.$mount();
document.body.appendChild(instance.$el);
}
//將隱藏方法傳給loading的hide屬性
loading.hide = function () {
instance.hide();
}
export default loading;
註冊及使用
註冊
在main.js
裏註冊
//引入loading.js
import loading from './components/loading'
Vue.prototype.$myloading = loading//展示loading
Vue.prototype.$hideloading = loading.hide//隱藏loading
使用
顯示loading框:
this.$myloading({
message: '請稍候',
count: 10
})
隱藏
this.$hideloading()