Vue:事件总线处理程序未定义
Vue: event-bus handler is undefined
我想在我的 vue 应用程序中实现事件总线。
首先我想调用事件总线来开始加载。
我调用 $on
的主要组件的脚本标记如下所示:
<script>
import store from '../store.js'
import EventBus from '../event-bus';
import Header from './includes/Header'
import Footer from './includes/Footer'
import Loading from './includes/Loading'
export default {
data() {
return {
isLoading: null
}
},
components: {
Header,
Footer,
Loading
},
mounted() {
EventBus.$on('isLoading'), function (payLoad) {
console.log(payload)
this.isLoading = payload
};
}
}
</script>
但是我得到了这个错误:
[Vue warn]: Error in event handler for "isLoading": "TypeError: handler is >undefined"
我该如何解决?
你有两个错误。它应该是这样的:
EventBus.$on('isLoading', (payLoad) => {
console.log(payload)
this.isLoading = payload
});
错误 1 是逗号前的结束 )
,导致 $on
在没有函数的情况下被调用。这就是导致警告消息的原因。结束 )
应该在最后,在 }
和 ;
之间。
错误2使用的是普通函数,导致this
函数内部不正确。箭头函数将保留周围范围的 this
值。
我建议使用 IDE 或可以解决此类问题的 linter。您的代码在语法上是有效的,但这些类型的错误可以通过合适的工具轻松检测到。
我想在我的 vue 应用程序中实现事件总线。
首先我想调用事件总线来开始加载。
我调用 $on
的主要组件的脚本标记如下所示:
<script>
import store from '../store.js'
import EventBus from '../event-bus';
import Header from './includes/Header'
import Footer from './includes/Footer'
import Loading from './includes/Loading'
export default {
data() {
return {
isLoading: null
}
},
components: {
Header,
Footer,
Loading
},
mounted() {
EventBus.$on('isLoading'), function (payLoad) {
console.log(payload)
this.isLoading = payload
};
}
}
</script>
但是我得到了这个错误:
[Vue warn]: Error in event handler for "isLoading": "TypeError: handler is >undefined"
我该如何解决?
你有两个错误。它应该是这样的:
EventBus.$on('isLoading', (payLoad) => {
console.log(payload)
this.isLoading = payload
});
错误 1 是逗号前的结束 )
,导致 $on
在没有函数的情况下被调用。这就是导致警告消息的原因。结束 )
应该在最后,在 }
和 ;
之间。
错误2使用的是普通函数,导致this
函数内部不正确。箭头函数将保留周围范围的 this
值。
我建议使用 IDE 或可以解决此类问题的 linter。您的代码在语法上是有效的,但这些类型的错误可以通过合适的工具轻松检测到。