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;

底层原理还不清楚,如有大佬知道请不吝赐教。

posted @   钱塘江畔  阅读(834)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示