使用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的值


免責聲明!

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



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