[Vuejs]-Pass the clicked element's data by using eventbus in Vue.js

0đź‘Ť

âś…

Here is my approach which worked for me (few changes):

@bbsimonbb, thank you for the answer, but I´m not going to use that approach, because its a bit overkill when compared to my small task.

In Patients.vue while looping patients, I have modified the click event:
Im actually passing the single element that is being clicked, which solved med a lot of time.

<div v-for="PatientData in storedPatients" class="col-12 col-sm-6 col-md-3 mb-3" :data-id="PatientData.content" @click="passPatientData(PatientData)" >

Before:

  @click="passPatientData"

After:

@click="passPatientData(PatientData)"

And then in my event bus im able to “work” with the data im passing:

methods: {
    passPatientData(element) {
      this.patientName = element.content;
      alert(this.patientName);

      eventBus.$emit("passPatientData", this.patientName);
    }
  }

The purpose is to pass the patientName to ViewPatient.vue file by using eventbus and call a new endpoint which looks like this: endpoint/patient/(patientName) . The result of the endpoint will then be the details of the single patient that has been clicked in patients.vue

It´s working. Hope it can be useful for others that is struggling with the same issue.

0đź‘Ť

You’ve decided not to use Vuex. That doesn’t mean you shouldn’t use a store. The simplest store is just an object in the data of your root Vue, passed around via provide/inject. Put your shared data in there.

This is a much simpler pattern to get your head around than an event bus. You get the shared state right out of Vue components, and because it’s just an object, that does nothing but store state, you will be more in control of what you have and how it’s working.

// Home.vue
export default {
    name: "home",
    provide: { mySharedData: this.mySharedData },
    data() {
        return {
            mySharedData: {
                patientData: {}
            }
        };
    },
    created() {
        fetch("http://patientData")
            .then(response.json)
            .then((patientData) => this.mySharedData.patientData = patientData)
    }
    ...

// Then, in all other components of your app...
export default {
        inject: ['mysharedData'],
        ...
    }

This way, you’ll be making full use of Vue reactivity to propagate your changes. You’ll need to understand how Vue makes properties reactive. In particular, you can’t just assign new props in mySharedData. The simplest way is to make sure all the props are there to start with. To do it on the fly, use Vue.set().

Leave a comment