vue頁面的定時刷新


setInterval

setInterval以指定時間為周期循環執行,一般用於刷新表單,對於一些表單的假實時指定時間刷新同步

在做一個項目的時候,會遇到要求一個頁面幾分鍾去定時刷新一下獲取最新數據的情況,需要用到 setInterval() 了,下面是自己使用的vue中查詢是否有未讀消息的通知的定時器。
在這里插入圖片描述
template標簽中消息通知的內容: 

<div class="btn-bell">
                    <el-tooltip effect="dark" :content="message?`有${message}條未讀消息`:`消息中心`" placement="bottom">
                        <router-link to="notify">
                            <i class="el-icon-bell"></i>
                        </router-link>
                    </el-tooltip>
                    <span class="btn-bell-badge" v-if="message"></span>
                </div>

script標簽中的部分內容

<script>
export default {
        data() {
            return {
                message: 0,  // 有幾條未讀的消息
                timer: null  // 定時器
            }
        },
        // 每20秒刷新一次
        created () {
            this.timer = setInterval(() =>{
                this.getNotReadCount()
            },1000* 20)
        },
        methods:{
            // 得到未讀的消息個數
            getNotReadCount () {
                // console.log('1232143')
                this.$axios.get('/api/notifications/notReadCount').then((res) =>{
                    if(res.data.code ===1){
                        this.message = res.data.data[0]
                        console.log('this.notifyReadCount' + this.message)
                    }
                })
            },
         // 可以判斷如果定時器還在運行就關閉 或者直接關閉
        destroyed () {
            clearInterval(this.timer)
        }
    }
</script>
setTimeout
只在指定時間后執行一次,一般用於延遲執行某方法或功能
<script>
//定時器 異步運行
function hello(){
alert("hello");
}
//使用方法名字執行方法
var t1 = window.setTimeout(hello,1000);
var t2 = window.setTimeout("hello()",3000);//使用字符串執行方法
window.clearTimeout(t1);//去掉定時器
</script> 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM