[Vuejs]-Getting an error when using event bus to communicate data?

0đź‘Ť

Use global singleton.

Better understand vuex

Vue.component('form-input', {
  template: '#form-input',
  props: ['model', 'config']
})

Vue.component('form-submit', {
  template: '#form-submit',
  props: ['model', 'config'],
  methods: {
    submitForm: function () {
      console.log(this.model)
    }
  }
})

new Vue({
  el: '#app',
  data: {
    model: {},
    config:{
      input1:{
        text: 'input1',
        id: 'input1'
      },
      input2:{
        text: 'input2',
        id: 'input2'
      },
      button: {
        text: 'Submit'
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
  <form-input :model="model" :config="config.input1"></form-input>
  <form-input :model="model" :config="config.input2"></form-input>
  <form-submit :model="model" :config="config.button"></form-submit>
</div>

<template id="form-input">
  <div class="row">
    <label>{{config.text}} <input type="text" v-model="model[config.id]"></label>
  </div>
</template>

<template id="form-submit">
  <div class="row">
    <button @click="submitForm">{{config.text}}</button>
  </div>
</template>
👤Mixa

0đź‘Ť

You seem to misunderstand the way an event bus works. When you call on, you’re saying “wait for someone to emit this event”. I don’t see that there’s any reason to expect that emitChatRoomVal will have been called at some time shortly after submitForm.

Since the data item is supposed to be shared, you might make it owned by the bus itself. Or you might define an event that requests the value of chatRoomVal, so that you can emit the request in your 2nd component, and the 1st component will fire emitChatRoomVal in response.

👤Roy J

Leave a comment