Sharing an array between two sibling components

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();

Answer №1

One effective strategy is to designate the parent as the central source of information. Essentially, when a new QR code is generated, the child component should send out an event using $emits to alert the parent, which can then save this data in an array.

With the parent now containing the relevant information, it becomes simple for it to share this data with all of its child components seamlessly.

Answer №2

Take a look at this code snippet:

Vue.component('home',{
  template: `<div>
    <h2>Home Component</h2>
    <button @click="sendQrCode">Check</button>
  </div>`,
  methods:{
    sendQrCode:function(){
      this.$root.$emit("codeSent",["code1","code2","code3"]);
    }
  }
});

Vue.component('history',{
  template: `<div>
    <h2>History Component</h2>
    {{ codes }}
  </div>`,
  data:function(){
    return {
      codes:null
    }
  },
  created(){
    let that = this;
    this.$root.$on("codeSent",(payload)=>{
      that.codes = payload;
    })
  }
  
});

new Vue({
  el:"#app"
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<html>
  <body>
    <div id="app">
      <home></home>
      <hr />
      <history></history>
    </div>
  </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The new pop-up window appears smaller than expected in Internet Explorer

There has been a bug report regarding the course opening in a smaller popup window. The JavaScript code used to open the popup is: course_window=window.open(urlString,"", "toolbar=0,directories=0,location=0,status=0, menubar=0,fullscreen=0,scroll ...

Are there any customizable actions available for the `yarn remove [package]` command, such as post-installation hooks?

I must execute a script following the completion of the following commands: yarn add [package] yarn remove [package] yarn upgrade [package] yarn install postinstall gets triggered after yarn add, yarn upgrade, and yarn install. However, it doesn't s ...

Stop the closure of confirmation box by disabling the space key

I've been working on a website that features a table for users to interact with. Within one column of the table, there are input boxes where users can write notes. Below each input box, there is a save button to store the entered notes in a database. ...

Completing Forms Automatically with AngularJS

Hello! I'm just starting out with ng and I need to make an autocomplete textbox that will initiate an AJAX call when the text is changed. The catch is that the minimum length required to trigger the AJAX call is 3 characters. However, once the user en ...

What could be causing the target to malfunction in this situation?

Initially, I create an index page with frames named after popular websites such as NASA, Google, YouTube, etc. Then, on the search page, <input id="main_category_lan1" value="test" /> <a href="javascript:void(0)" onmouseover=" window.open ...

Using a wildcard (*) to select elements with JQuery

I'm just starting to learn about JQuery and could use some help. I want to select multiple elements but I only know part of their Ids: for example: <div id="element32422455">Some content</div> <div id="element68475124">Some content& ...

What steps do I need to take to successfully implement a $.fn. function that runs automatically when it is called?

I'm struggling with the following piece of code: function init() { var $contentButtonPanel: JQuery = $('#content-button-panel') $contentButtonPanel .find('.arbo .toggle, .collapsible-list li:has(ul) > ...

Upon loading, the Carousel is visible instead of being hidden, which is contrary to its intended behavior

Any help would be greatly appreciated as I am struggling with creating a web page featuring tabs for "London, New York, Shanghai". The initial page displayed is the "welcome" page with the other tabs hidden on load. I successfully implemented a carousel f ...

Navigating a Vue.js realm: Transferring card button ID to backend URL pathway upon clicking

Within my DisplayBooks.vue component, I have implemented a feature where users can update a book card by clicking on the ADD TO BAG button. This update is triggered by calling the handleCart() method which takes care of updating the book based on its id. M ...

Error: AngularJS is experiencing an injector module error that has not been caught

I have set up an Angular boilerplate that includes various elements such as meta tags, CDN links, and script tags. However, I am encountering a persistent error in my console and cannot figure out the root cause of it. https://i.stack.imgur.com/qPGby.png ...

The image filter plugin is functioning properly in one project, however, it is not working in

After successfully using a plugin from w3schools to filter elements in one project, I encountered an issue when attempting to implement it in another project. Here is the link to the problematic code pen: https://codepen.io/zakero/pen/mZYBPz If anyone ca ...

Get the desired text following the second <br> tag using jQuery

I am trying to identify a specific string that comes after the second occurrence of <br> tag and then check if this string contains any numbers. If there are no numbers present, I want an alert to be shown. The code for performing this action is func ...

Strategies for deploying on production as you develop a fresh Nuxt application

What are some recommended strategies for deploying a Vue/Nuxt project on production, especially for larger applications with lengthy build times? Typically, running the command npm run build Causes the app to be inaccessible to users until the build proc ...

Is it possible for Node.js to not automatically restart the server when modifying .js files?

Right now I have node-supervisor set up to detect changes in .js files, and while it works well, I've realized that it restarts the server every time a js file is saved. Is there a way to save a server-side .js file without triggering a server restart ...

Incorrectly resolving routes in the generate option of Nuxt JS's .env configuration file

Having trouble using Nuxt JS's 2.9.2 generate object to create dynamic pages as static files by referencing a URL from my .env file: nuxt.config.js require('dotenv').config(); import pkg from './package' import axios from 'a ...

Some packages seem to be missing in React Native

I decided to incorporate a project I cloned from GitHub into my React Native app by placing it in a separate folder outside of the app. After running npm link on the project and linking it to my own project, I encountered an issue when attempting to run i ...

Troubleshooting issues with AngularJS routing

Having trouble clicking on the show button and seeing anything displayed. I've spent a lot of time on this without success, can someone please assist. Files.... app.js controller.js index.html show.html index.html <html ng-app='Java4sApp& ...

The OrbitControls function is not able to be instantiated as a constructor

I've been working on creating a WebVR environment for the past week using Three.js, but I'm having trouble getting the VR controls to function correctly. Here are some of the things I've tried: 1. Adding packages in my node_modules and imp ...

Using Jquery to Retrieve the Attribute Value from an HTML Element

I am currently developing an interactive online quiz application that is organized by chapters, with each chapter having its own quiz. Users can navigate through the chapters via a menu and start quizzes by clicking on a button after loading the chapter co ...

Using a variable in VueJS to reference an external template file

Is there a way for me to choose a component template based on the client I am working with? I have set the client ID in the env file and what I am looking for is something similar to the following: <template :src="'../themes/' + process.env.V ...