简体   繁体   English

如何使用事件总线在 vuejs 中的两个组件之间共享数据

[英]How to share data between two component in vuejs with Event Bus

I am trying to implement a global event bus in order to send a variable from component A to component B.我正在尝试实现全局事件总线,以便将变量从组件 A 发送到组件 B。

Here is the component A code:这是组件A代码:

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

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

Here is the component B code:这是组件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>

I'm getting this error when component B is displayed:显示组件 B 时出现此错误:

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

How to solve this?如何解决这个问题?

In your template you are referencing commandes在您的模板中,您正在引用commandes

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

but your data doesn't return it, it returns commande但你的数据没有返回它,它返回commande

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

Update your data and bus listeners:更新您的数据和总线侦听器:

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

...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM