Within my 'Home' component, users have the ability to create QR codes. I have implemented a method that generates an array of these QR items. Now, the challenge lies in passing this array to another component that is a sibling and not located within a parent-child or child-parent relationship.
My attempted solution involved creating an eventBus, but unfortunately, it did not yield successful results.
MainApp.vue
<template>
<div class="container-fluid">
<app-header></app-header>
<div class="row">
<div class="col-sm-12">
<router-view></router-view>
</div>
</div>
</div>
</template>
<script>
import { eventBus } from './main';
import Header from './components/Header.vue';
export default {
data() {
return {
urls: []
}
},
created() {
eventBus.$on('updateUrls', (data) => {
this.urls.push(this.data);
})
},
components: {
'app-header': Header
}
}
</script>
<style>
</style>
HomeComponent.vue
<template>
<div>
<h2>Welcome to QR Code Generator</h2>
<p>Generate custom QR codes for your website</p>
<hr>
<div class="form-group">
<label>Enter your website address:</label>
<input type="text" class="form-control" v-model="address">
</div>
<a :href="url" target="_blank" class="btn btn-primary" :disabled="!address">Generate</a>
<button class="btn btn-primary" :disabled="!address" @click="saveData">Save</button>
<button class="btn btn-secondary" @click="clearInput" :disabled="!address">Clear</button>
</div>
</template>
<script>
import axios from 'axios';
import { eventBus } from '../main';
export default {
data() {
return {
address: '',
prefix: `https://www.qrtag.net/api/qr_4.png?url=`,
}
},
computed: {
url() {
const url = this.prefix + this.address;
return url;
}
},
methods: {
clearInput() {
this.address = ''
},
saveData() {
const data = {
url: this.url,
date: new Date()
}
eventBus.$emit('updateUrls', this.data);
},
}
}
</script>
HistoryView.vue
<template>
<div>
<router-link tag="a" class="nav-link" to="/dashboard">Generate another QR code</router-link>
<p :urls="urls" v-for="link in urls">{{ link.url }}</p>
</div>
</template>
<script>
import { eventBus } from '../main';
export default {
props: ["urls"],
data() {
return {
}
}
}
</script>
main.js
export const eventBus = new Vue();