你在哪里监听 VueJS 中发出的事件?

Where do you listen for emitted event in VueJS?

设置如下:

export default Vue.extend({
 name: 'Home',
 computed: {
   ...mapState('user', ['card']),
 },
 created() {
  this.fetchData();
 },
 mounted() {
  this.$once('dataLoaded', () => {
    if (!this.card) {
      this.showWarning();
    }
  });
},
watch: {
  '$route': 'fetchData'
},
methods: {
  async fetchData() {
    await Promise.all([...]);
    this.$emit('dataLoaded');
  },
  showWarning() {
    // Vue global Plugin for creating a banner
    Notify.create();
  }
 }
});

我在 mounted 生命周期中附加了监听器,但我想知道我是否应该在 created() 中附加它。在这两种情况下它似乎都工作正常因此我的问题是是否有一些最佳实践或者我在这里错过了一些重要的事情。

谢谢!

你把事情复杂化了。 不需要 emit 因为您只向我们展示了一个组件
就这样吧:

methods: {
  async fetchData() {
    await Promise.all([...]);
    this.myMethod()
  },
  myMethod() {
    if (!this.card) {
      this.showWarning();
    }
  }