VUE 组件里使用定时器自动刷新数据

使用 window.setInterval()

<template>
  <div class="hello">
    <h2>Count: {{count}}</h2>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "HelloWorld",
  props: {
    msg: String
  },

  data() {
    return {
      count: 0
    };
  },

  created() {
    this.getRandomNumber();
    this.timer = setInterval(this.getRandomNumber, 5000);
  },

  methods: {
    getRandomNumber() {
      axios
        .get("https://wordpress.org/news/wp-json/wp/v2/posts", {
          params: {
            per_page: 1
          }
        })
        .then(response => {
          // handle success
          console.log(response);
          this.count = Math.floor(Math.random() * 10);
        })
        .catch(error => {
          // handle error
          console.log(error);
          this.count = 0;
        });
    },

    cancelAutoUpdate: () => {
      clearInterval(this.timer);
    }
  },

  beforeDestroy() {
    clearInterval(this.timer);
  }
};
</script>