頁面代碼如下:
<!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的值