1. 程式人生 > 其它 >Vue中使用PubSub-js進行元件間通訊時出現‘publish‘ of undefined異常解決辦法

Vue中使用PubSub-js進行元件間通訊時出現‘publish‘ of undefined異常解決辦法

技術標籤:vuevuepubsub-js

解決辦法:如果釋出訊息的元件中使用的程式碼形如this.PubSub.publish(‘xxx’, test),就將其中的this.去掉,即直接使用PubSub.publish(‘xxx’, test)。

在vue中進行元件間通訊時,發現控制檯出現如下異常:

[Vue warn]:Error in callback for watcher "xxx": "TypeError: Cannot read property 'publish' of undefined"

經過網上反覆查詢,未找到有用資訊,於是就嘗試將this.PubSub.publish(‘xxx’, test)中的this.去掉,居然成功了。究其原因,尚不明確。

並且,經過實測發現,將元件中的匯入語句import PubSub from 'pubsub-js’刪除,也不影響pubsub-js功能。