【问题标题】:Have $emit() execute synchronously after a function in Vue在 Vue 中的函数之后同步执行 $emit()
【发布时间】:2019-04-05 01:32:17
【问题描述】:

我正在尝试将布尔变量设置为 false 以在 Vue 2 中打开对话框之前关闭菜单。

public saveScreens() {
    this.showThreeDotMenu = false
    this.$emit('save-screens')
}

我想同步执行这两行,但是无论如何我都找不到在分配完成之前发生的 $emit。

我尝试将赋值语句外推到它自己的函数设置为异步,然后在 saveScreens() 中点击该函数,然后 .then( () => this.$emit('save-screens')) 但是这个还是不行。

无论我尝试过什么,电子消息框都会打开,然后在关闭后布尔值设置为 false,然后我关闭的菜单。

有什么方法可以等到我使用 v-if 的条件 HTML 完成隐藏,然后再执行一个函数?

使用 Electron 1.8.8 和 Vue 2.x+

【问题讨论】:

  • 想要同步执行这两行,但是无论如何我都找不到 $emit 在分配完成之前发生。 1)它是同步的 2)它是在分配完成之后——别无他法。
  • 听起来你可能想使用Vue.nextTick
  • @RoyJ 不幸的是也没有用。
  • 你有没有机会制作一个演示这个问题的小提琴?我不完全清楚正在发生的事情与您想要发生的事情。
  • 嗯不是真的,我的意思是我只是试图通过将布尔值更改为 false 来隐藏一个带有 v-if 的 html div(包含一个菜单),就在我打开电子对话框之前(@987654322 @)。我并没有真正使用 Jsfiddle 并且不确定你是否可以在那里获得电子?但这就是试图将 v-if 检查的布尔变量设置为 false,然后发送到执行消息框和其他一些不相关功能的组件。

标签: vue.js vuejs2 electron


【解决方案1】:

我想出的唯一直接的解决方案是使用setTimeout 来延迟对话框显示(如cmets 中所述,nextTick 没有解决问题)。我制作了一个演示 sn-p,您可以在其中更改超时间隔。在我的浏览器上运行大约 10 毫秒。我建议使用 50 之类的东西在任何地方都非常安全。

我会使用v-show 而不是v-if 来表示将要隐藏并再次显示的内容。

new Vue({
  el: '#app',
  data: {
    showMenu: true,
    delay: 10
  },
  methods: {
    showDialog() {
      this.showMenu = false;
      setTimeout(() => {
        alert('this is a dialog');
        this.showMenu = true;
      }, this.delay);
    }
  },
  components: {
    threeDotMenu: {
      template: '#three-dot-menu-template',
      props: ['show'],
      methods: {
        openDialog() {
          this.$emit('save-screens');
        }
      }
    }
  }
});
.menu {
  background-color: #fee;
  padding: 2em;
}
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <label>Delay: <input type="number" v-model="delay"></label>
  <three-dot-menu :show="showMenu" @save-screens="showDialog"></three-dot-menu>
</div>

<template id="three-dot-menu-template">
  <div class="menu" v-show="show">
    this is the menu
    <button @click="openDialog">Open dialog</button>
  </div>
</template>

【讨论】:

  • 我最终使用了 25 毫秒的延迟,并查看了 v-show 并将其切换到它。感谢您的回答,这对我来说有点奇怪,我不得不使用超时。
猜你喜欢
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-11
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多