Hello I have this problem:in main.js I have a global function getSites, needed to retrive a list of sites from API.
This function work with async/await and returns data sites asynchronously.
I also have a global variable called lockSitesLoading which i set to true when i start to fetch data from API, I need this to prevent client to make a new request to server.
In the first function getSites I need to check this variable lockSitesLoading and, if it's true, start to watch it till it becomes false. At this point I want to call getSites recursively.
The problem starts now, because when i start watch the variable this function doesn't wait for the variable to become false, but returns undefined.
Here there is my code:

Compartant.vue:(用谷歌翻译翻译)

  async mounted() {
    let vm = this;
    const sites = await vm.getSites();
    vm.sites = sites.data
  },

Main.js:

 async getSites() {
      let vm = this;
      if (vm.$store.state.lockSitesLoading) {
        vm.$watch('$store.state.lockSitesLoading', () => vm.getSites());
      } else {
        return vm._getSitesOnline();
        //this is the function that effectively get datas from server
      }

我试着用这种方法解决它,但行不通.有什么好主意吗?

推荐答案

基本上,需要有一个等待的promise :

  let unwatch;

  await new Promise(resolve => {
    unwatch = vm.$watch('$store.state.lockSitesLoading', loading => {
      if (!loading) {
        resolve();
      }
    }, { immediate: true });
  });

  unwatch();

  await vm._getSitesOnline();

请注意,如果lockSitesLoading出于某种原因阻止执行,这将导致内存泄漏.

这可能是使用Compostion API和VueUse Composables实现这一点的更干净的方法.

Vue.js相关问答推荐

Vutify-v-工具提示-不使用键盘轻击按钮显示

nuxt.js auth 始终重定向到登录,而不是允许转到带有 auth: false 的页面,

JSDoc 单文件 Vue 组件

nuxt.js - 预加载 .woff 字体加载为@font-face

如何在Typescript语言Vuejs中使用watch功能?

Vue cli 3项目,图像路径中的动态src不起作用

Vuetify - 如何保持第一个扩展面板默认打开,如果我打开另一个面板,其他面板应该关闭?

如何在 Vue.js 中触发点击 ref

单击链接会更改 url,但不会更改页面上的内容/数据

v-model 不会检测到 jQuery 触发事件所做的更改

Vue-test-utils:在单个测试中多次使用 $nextTick

如何将 v-if 与 Vue.js 中的值进行比较

如何在 Vue 中动态创建组件上获取更新的 $refs?

Select 下拉列表中的复选框后如何清除 v-autocomplete(多个)搜索输入?

如何将项目推送到 Vuejs 中数据对象的数组中? Vue 似乎没有关注 .push() 方法

axios 拦截器响应未定义

是否有 v-cloak 逆?

Vue 2.0 设置路由 - 不要使用new来产生副作用

在 Vuex 模块中进行继承的方法

超过最大调用堆栈大小 Vuetify