vue+axios定時刷新頁面數據


1. 背景

最近在做實時數據處理,想做一個頁面實時展示

2. html代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自動獲取笑話</title>
    <script src="js/vue.js"></script>
    <script src="js/axios.min.js"></script>
</head>
<body>
<div id="app">
    <input type="button" value="手動獲取笑話" @click="createJokes">
    <p v-for="(ele, index) in jokes">{{index + 1}}. {{ele}}</p>
</div>
</body>

<script>
    var app = new Vue({
        el : "#app",
        data : {
            jokes : [],
            intervalId : null
        },
        methods:{
            createJokes : function(){
                var t = this;
                axios.get("https://autumnfish.cn/api/joke/list", {params: {"num" : 5}}).then(function(response){
                    t.jokes = response.data.jokes;
                },function(error){});
            },
            // 定時刷新數據函數
            dataRefreh : function() {
                var t = this;
                // 計時器正在進行中,退出函數
                if (this.intervalId != null) {
                    return;
                }
                // 計時器為空,操作
                this.intervalId = setInterval(() => {
                    axios.get("https://autumnfish.cn/api/joke/list", {params: {"num" : 5}}).then(function(response){
                        console.log(response.data.jokes)
                        t.jokes = response.data.jokes;
                    },function(error){});
                }, 5000);
            },
            // 停止定時器
            clear() {
                clearInterval(this.intervalId); //清除計時器
                this.intervalId = null; //設置為null
            },
        },
        created(){
            this.createJokes();
            this.dataRefreh();
        },
        destroyed(){
            // 在頁面銷毀后,清除計時器
            this.clear();
        }
    })

</script>
</html>
  1. 問題及解決方法
    初版代碼運行后,頁面數據不會自動定時刷新,並且報錯如下:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 

原因是直接調用this.jokes = response.data.jokes;
解決辦法是:

var t = this;
t.jokes = response.data.jokes;

底層原理還不清楚,如有大佬知道請不吝賜教。


免責聲明!

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



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