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

How to reload a GET request in created . Vue.js

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

我创建的:

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"));
    }
  },

你能帮我实现 setInterval 到我的 get 请求吗?

谢谢

  1. 尝试使用 setInterval,例如:

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

  1. 更聪明的解决方案可能是:在 nuxt 代理服务器或后端使用 POST 请求,例如 axios.post('/data', payload) 并连接 websockets,您可以使用 pusher 为此。最终的逻辑是:用户添加一些数据 => post 到服务器 => 服务器发出 websockets 事件 => vuex 监听事件并且数据将在所有选项卡中响应。