使用vue实现定时发送异步请求更新数据

页面代码如下:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>vue-test</title>
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
<div id="app">
    当前数字数:{{num}}
</div>

<script>
    var app = new Vue({
        el:'#app',
        data:{
            num:0,
        //定时器 timer:
'' }, created :function () { this.getDate();
        //定时器要执行的任务和间隔时间(毫秒)
this.timer = setInterval(this.getDate, 3000); }, computed:{ }, methods:{
      //axios异步请求 getDate:
function () { var that = this; axios.get("/getNum?num=" + that.num).then(function (response) { that.num = response.data.age; }) } }, mouted:function(){ }, beforeDestroy:function() {
        //关闭窗口后清除定时器 clearInterval(
this.timer); } }) </script> </body>

后台接口:

@RestController
public class NumberController {

    @RequestMapping("/getNum")
    public DemoDto get(int num){
        DemoDto demoDto = new DemoDto();
        demoDto.setAge(num+10);
        return demoDto;
    }
}
注意:这里是两个类
@Controller
public class PageControler {
@RequestMapping("/")
public String home(){
return "index.html";
}
}

效果如下,进入该页面会不断请求更新num的值

posted @ 2020-08-19 14:00  指路为码  阅读(2631)  评论(0编辑  收藏  举报