【问题标题】:Emit Events and On Vuejs 2发出事件和在 Vuejs 2
【发布时间】:2017-10-05 20:50:01
【问题描述】:

嗨,这是我的父自定义事件

bus.$emit('updated-users', 'Sample Data')

我的组件

bus.$on('updated-users', data => this.lastname = data)

这个有效。

使用回调不起作用。

bus.$on('updated-users', function(data){
        //data is displayed in the console log.
        console.log(data)
        //This doesn't work. 
        this.fetchedUsersData()
    })

我需要触发一个方法,但它不起作用。我找不到任何触发方法的示例。请帮忙。

【问题讨论】:

  • 未绑定 this 在您的函数中使用。
  • 嗨,你是什么意思未绑定this。只有fetchedUsersData()吗?
  • @kirqe 这个例子是从孩子到父母。我的是从父母到孩子。还是一样的概念吗? TY
  • @kirqe 您发布的内容需要数据才能触发功能。我认为这不是重复的。 TY
  • 在这两种情况下,您都在使用回调函数,您只是以不同的方式定义函数,具体问题是箭头函数和常规函数之间绑定this 的方式不同。箭头函数是词法绑定的,这意味着 this 将指向 Vue。在第二个示例中,this 可能会指向 bus,它没有 fetchedUsersData 方法。

标签: vue.js components


【解决方案1】:

你可以试试这个

created () {
 bus.$on('updated-users', fetchedUsersData)
},
methods: {
 fetchedUsersData(){
  //the fetched user data
  console.log('the fetched user data')
 }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 2018-03-17
    • 2017-11-11
    • 2018-12-29
    • 2017-12-25
    • 2017-11-02
    • 2019-11-21
    相关资源
    最近更新 更多