如何在created中重新加载GET请求 Vue.js

问题描述

我正在从Rails API后端获取数据,我想做的是每15秒重新加载一次获取请求,因此,如果后端发生某些变化(例如,我以另一条路线向后端发出了发布请求),重新加载并获取当前数据。

我创建的:

created() {


    if (!localStorage.signedIn) {
      this.$router.replace("/");
    } else {
      this.$http.secured
        .get("/api/v1/records")
        .then(response => {
          console.log(response.data);
          this.records.splice(0,this.records.length - 1,...response.data);
        })
        .catch(error => this.setError(error,"Something went wrong"));
      this.$http.secured
        .get("/api/v1/templates")
        .then(response => {
          this.templates = response.data;
        })
        .catch(error => this.setError(error,"Something went wrong"));
      this.$http.secured
        .get("/api/v1/data")
        .then(response => {
          this.datas = response.data;
        })
        .catch(error => this.setError(error,"Something went wrong"));
    }
  },

您能帮我为我的get请求实现setInterval吗?

谢谢

解决方法

  1. 尝试使用setInterval,例如:

mounted() {
    this.intervalData = setInterval(this.getdata,15000)
  },destroyed() {
    clearInterval(this.intervalData)
  },methods: {
    getData() {}
  },

  1. 更聪明的解决方案可能是:在nuxt代理服务器或后端中使用POST请求,例如axios.post('/ data',有效负载)并连接网络套接字,您可以使用pusher。最终的逻辑是:用户添加一些数据=>发布到服务器=>服务器发出websockets事件=> vuex侦听该事件,并且所有选项卡中的数据都是反应性的。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...