【问题标题】:Vue object passed through emit not recognized after listened in the other component在其他组件中侦听后无法识别通过发射的Vue对象
【发布时间】:2018-07-02 13:32:30
【问题描述】:

我有两个组件,组件 A 和组件 B。 在 componentA 中,我有一个 click 事件,它触发一个将用户对象作为参数传递的方法,然后使用事件总线发出该对象。当我成功收听 componentB 中的发射时,我已将发射的对象分配给一个变量,我 console.log 出它显示该对象的变量,但是当我再次 console.log 时 Event.$once 之外的变量对象消失了。 任何帮助,将不胜感激 :) 谢谢!

这是我的代码:

组件A

showUserStats(user) {
    EventBus.$emit('userInfo', user);
    this.$router.push({
      name: 'componentB',
      params: { id: user._id }
    })
  }

组件B

created() {
      EventBus.$once('userInfo', (user) => {
        this.userInfo = user
        console.log('userInfo', this.userInfo);
      });
      console.log('userInfo outside EventBus', this.userInfo);
    }

Here is the image of the output

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    发生这种情况是因为您正在控制台登录 created 生命周期事件。 $once 调用之外的控制台日志在组件创建时立即调用(当未分配用户信息时),但 $once 中的 console.log 仅在事件发出时发生,而变量 /数据已分配。

    与 cmets 一致:您不能仅仅抛出延迟并期望它能够工作,因为它基于事件触发。你没有告诉我们何时调用showUserStats,所以我不知道这个事件何时发出。

    关于计算的值,它应该可以工作,因为它会在分配用户信息时更新,但您需要添加一个检查以检查何时不是这样,如下所示:

    computed: {
      fullName () {
        return this.userInfo ? this.userInfo.name + ' ' + this.userInfo.surname : ''
      }
    }
    

    除非已分配用户信息对象,否则它将显示空白(注意:您可能需要根据您在数据 () 中初始化 userInfo var 的方式来更改检查)

    【讨论】:

    • 感谢您的帮助,但我尝试延迟 1 秒仍然没有运气:( 我想在我的计算方法中使用该变量。
    • 计算:{ fullName() { return this.userInfo.name + ' ' + this.userInfo.surname; } }
    • 奇怪的是,当我调用 API 检索用户信息时它工作正常
    • 据我了解,您每次单击右键时都试图触发事件?如果是这样,那么您应该使用 $on 而不是 $once
    猜你喜欢
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 2018-10-22
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多