vuejs2 - vue js通过全局事件总线传递数据不起作用
问题描述
使用 vue cli,我创建了一个带有两个嵌套组件的简单 vue 应用程序。我想通过单击组件 1 中的 h1 标签在它们之间传递数据(更结构化的方法建议使用 vuex,但这是一个非常简单的应用程序,用于传递简单数据用于测试)。
单击 h1 我收到一个错误,但我不明白这一点。错误说
[Vue warn]: Error in event handler for "titleChanged": "TypeError: Cannot read property 'apply' of undefined"
(found in <Root>)
我的代码如下
main.js
import Vue from 'vue'
import App from './App.vue'
import Axios from 'axios'
Vue.config.productionTip = false
Vue.prototype.$http = Axios
export const bus = new Vue();
new Vue({
render: h => h(App),
}).$mount('#app')
应用程序.vue
<template>
<div>
<comp-1 v-bind:title="title"></comp-1>
<comp-2 v-bind:title="title"></comp-2>
</div>
</template>
<script>
import comp-1 from './components/Comp-1.vue'
import comp-2 from './components/Comp-2.vue'
export default {
components: {
'comp-1': comp-1,
'comp-2': comp-2
},
data() {
return {
title: "my title"
}
}
}
</script>
<style scoped>
</style>
comp-1.vue
<template>
<header>
<h1 v-on:click="changeTitle">{{ pTitle }}</h1>
</header>
</template>
<script>
import {bus} from '../main'
export default {
props: {
title: {
Type: String
}
},
data() {
return {
pTitle: ''
}
},
created: function() {
this.pTitle = this.title
},
methods: {
changeTitle: function() {
this.pTitle = 'I have changed my title!'
bus.$emit('titleChanged', this.pTitle)
}
}
}
</script>
<style scoped>
</style>
comp-2.vue
<template>
<footer>
<p>{{ title }}</p>
</footer>
</template>
<script>
import {bus} from '../main'
export default {
props: {
title: {
Type: String
}
},
data() {
return {
pTitle: ''
}
},
created() {
this.pTitle = this.title;
bus.$on('titleChanged'), (data) => {
this.title = data
}
}
}
</script>
<style scoped>
</style>
解决方案
在创建 comp-2 组件时,事件处理程序有错误
像这样改变它:
bus.$on("titleChanged", data => {
this.title = data;
});
推荐阅读
- jquery - 提交动态生成的按钮
- c# - 我可以在同一接口的多个实现上“隐式”调用方法吗?
- java - Optaplanner VRPTW“验证该 sourceVariableName 变量的输入问题的一致性”
- android - Flutter:如何修复多行启用文本字段底部的 SuffixIcon?
- azure-web-app-service - 从 ASP.NET CORE WEB API 向应用程序洞察添加请求
- javascript - 如何立即更新子组件中的父状态
- salesforce - 无法在 SFCC Demandware 中保存用户选择的选项列表值
- c++ - 在 Linux 上将正在运行的应用程序中的共享对象热更新到新版本
- javascript - Cordova webview + 角度
- java - Spring Boot JPA:GetRequest 没有输出