首页 > 解决方案 > Vue 条件轮询

问题描述

var page = new Vue({
    el: '#content-page',
    data: {
        token: null
    },

    methods: {},
    mounted: function () {
        //get token object from API
    }
});

令牌具有syncStatus可以是inProgress或的属性completed。我想要一个条件轮询,它将继续调用 API,直到 syncStatus 完成值。

我可以做这样的事情:

var page = new Vue({
    el: '#content-page',
    data: {
        token: null
    },

    methods: {
        //Method-get-token
        //In axios.then if syncStatus is inProgress call this method again
    },
    mounted: function () {
        //get token object from API
        //if syncStatus is inProgress call method-get-token
    }
});

但我认为必须有一些更好的方法来做到这一点。

有什么建议么?

标签: javascriptvue.jsvuejs2

解决方案


假设你没有商店

您可以添加一个数据属性来保存syncStatusthen 在挂载函数中的值,有条件地调用 api 以继续检查要更改的值。syncStatus然后添加一个观察者在值变化时做魔术

与此类似的东西

data() {
  return {
    syncStatus: 'notStarted' //you should think of having a default value to this
  }
},
mounted() {
  window.setInterval(()=>{
    //call the api conditionally
    if (syncStatus === 'inProgress'){
      //call the api
    }
  },MilliSeconds)
},
watch: {
  syncStatus: function(newValue) {
    //do magic when the value changes
  }
}

推荐阅读