前言:在vue项目中使用pubsub发生错误
** vue.esm.js?efeb:591 [Vue warn]: Error in mounted hook: "ReferenceError: PubSub is not defined" **
原因1:未安装pubsub
1.参照官网地址安装:https://www.npmjs.com/package/pubsub-js
Getting PubSubJS
There are several ways of getting PubSubJS
- Install via npm (npm install pubsub-js)
- Use it directly from a CDN directly
- http://www.jsdelivr.com/#!pubsubjs
- https://cdnjs.com/libraries/pubsub-js
- https://unpkg.com/pubsub-js
- Download a tagged version from GitHub
2.首先必须导入模块:
import PubSub from 'pubsub-js'
3.运行出现问题 This dependency was not found:执行如下命令
npm install --save .pubsub-js
如果上面都没有问题正好是在watch中调用不能使用this,如下就会出错
vue.esm.js?efeb:1741 TypeError: Cannot read property 'publish' of undefined
- 错误代码
watch: {
test(val) {
//注意:这是错误代码
this.PubSub.publish("test", val);
}
}
- 正确代码
watch: {
test(val) {
//正确代码
PubSub.publish("test", val);
}
}
注意:本文归作者所有,未经作者允许,不得转载