在其中一个组件中触发了$ emit事件(它显示在Vue.js开发工具控制台中),但是,接收端的组件无法正常工作。目的是从表单内的多个输入字段中收集数据,并将其显示在多步骤表单内的另一个组件中。我似乎找不到问题。我无法获取要在侦听组件中显示的数据。
app.js文件:
import Vue from 'vue'
import VueRouter from 'vue-router'
export const eventBus = new Vue();
Vue.use(VueRouter)
import App from './views/App'
import petsInfo from './views/petInfo'
import paymentInfo from './views/paymentInfo'
import confirmation from './views/confirmation'
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/',
name: 'pets',
component: petsInfo
},
{
path: '/payment',
name: 'payment',
component: paymentInfo
},
{
path: '/confimation',
name: 'confirmation',
component: confirmation
},
],
});
const app = new Vue({
el: '#app',
components: { App },
router,
});
发射组件:
<template>
<div class="container">
<input type="text" class="form-control" id="name" placeholder="Name" v-
model="name">
<router-link :to="{ name: 'payment' }" class="next-finish-btn"
@click.native="handleSubmit">Next</router-link>
</div>
</template>
<script>
import { eventBus } from '../app';
export default {
data () {
return {
name: ''
}
},
methods: {
handleSubmit() {
eventBus.$emit('form-submitted', this.name)
},
}
}
</script>
听/接收组件:
<template>
<div class="container">
{{ name }}
</div>
</template>
<script>
import { eventBus } from '../app';
export default {
data () {
return {
name: ''
}
},
methods: {
mounted() {
eventBus.$on('form-submitted', data => {
this.name = data
})
}
}
}
</script>