我正在尝试长时间使用 Vue$emit
和$on
功能,但我仍然没有得到任何解决方案。我只创建了两个页面的简单消息传递页面。一个是Component Sender
and和Component Receiver
添加eventbus
的功能。$emit
$on
我声明$emit
了$on
功能,但我不知道我在哪里犯了错误。
请帮助一些人。
组件发送者:
<script>
import { EventBus } from '../main';
export default {
name: 'Send',
data () {
return {
text: '',
receiveText: ''
}
},
methods: {
sender() {
EventBus.$emit('message', this.text);
this.$router.push('/receive');
}
}
}
</script>
组件接收器:
<script>
import { EventBus } from '../main';
export default {
name: 'Receive',
props: ["message"],
data () {
return {
list: null
}
},
created() {
EventBus.$on('message', this.Receive);
},
methods: {
Receive(text){
console.log('text', text);
this.list = text;
},
save() {
alert('list', this.list);//need to list value but $emit is not working here
}
}
}
</script>
路由器视图:
const router = new Router({
mode: 'history',
routes: [
{
path: "/",
name: "Send",
component: Send
},
{
path: "/receive",
name: "Receive",
component: Receive,
props: true
}
]
})
主.JS
import Vue from 'vue'
import App from './App.vue'
import router from './router';
export const EventBus = new Vue();
new Vue({
el: '#app',
router,
render: h => h(App)
})