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