Как обмениваться данными между двумя компонентами в vuejs с помощью шины событий - PullRequest
0 голосов
/ 06 мая 2020

Я пытаюсь реализовать глобальную шину событий, чтобы отправить переменную из компонента A в компонент B.

Вот код компонента A:

data () {
            return {                
            commandes: [],
            }
        },

envoyer() {                                 
                this.$eventBus.$emit('commande', this.commandes);
            }, 

Вот Код компонента B:

<template>
    <div class="container">
        <div class="row justify-content-center">
              <!-- Table row -->
              <div class="row">
                <div class="col-12 table-responsive">
                  <table class="table table-striped">
                    <thead>
                    <tr>
                      <th>Qté</th>
                      <th>Produit</th>
                      <th>Subtotal</th>
                    </tr>
                    </thead>
                    <tbody>
                      <tr v-for="(commande, index) in commandes" :key="index">
                        <td>{{ commande.quantite }}</td>
                        <td>{{ commande.produit_id }}</td>
                        <td>{{ commande.montant }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                <!-- /.col -->
              </div>
        </div>
    </div>
</template>

<script>
    export default {
      data() {
          return {
            commande: [],
          }
        },

        methods: {         
        },

        mounted() {
          this.$eventBus.$on('commande', (commandes) => {
            this.commande = commandes;
            console.log(commandes);
          })
        }
    }
</script>

Я получаю эту ошибку, когда отображается компонент B:

[Vue warn]: Property or method "commandes" is not defined on the instance but referenced during render.

Как решить эту проблему?

1 Ответ

0 голосов
/ 06 мая 2020

В вашем шаблоне вы ссылаетесь на commandes

<tr v-for="(commande, index) in commandes" :key="index">

, но ваши данные не возвращают его, он возвращает commande

data() {
   return {
    commande: [],
   }
}

Обновите свои данные и слушателей шины :

data() {
   return {
    commandes: [],
   }
}

...

this.$eventBus.$on('commande', (commandes) => {
  this.commandes = commandes;
  console.log(commandes);
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...