1. 程式人生 > 實用技巧 >使用vue實現定時傳送非同步請求更新資料

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