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

时间:2019-10-31 14:41:13

标签: javascript vue.js event-handling

这是设置:

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()中使用它。在这两种情况下似乎都可以正常工作,因此我想知道是否有一些最佳做法,或者我错过了重要的事情。

谢谢!

1 个答案:

答案 0 :(得分:0)

您使事情变得过于复杂。 不需要emit,因为您只向我们展示了一个组件
就是这样:

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