What is the best way to locate the Vue component I need to share data with?

Seeking guidance on structuring my Vue app. It features an interactive map where users can click on items, triggering a side panel to display related information. The side panel is enclosed in a new Vue(...) instance (perhaps referred to as a Vue component?). Currently, I declare each Vue component under the window object like so:

map.on('click', e => window.sidepanel.thingName = e.feature.thingName);

The code for the side panel and the map resides in separate modules with limited need for communication.

While my current method works adequately, I am curious about alternative patterns that don't rely on global variables.

Answer №1

Creating a new Vue instance with <code>new Vue()
is referred to as a vue instance, also known as vm

If you are working within constraints, I believe your approach is reasonable. There are a few alternatives that you can consider:

  1. One option is to create an event bus (which essentially functions as a vue instance) to manage shared events. This approach allows you to avoid delving deep into components but might introduce additional complexity. You can find more information at https://alligator.io/vuejs/global-event-bus/
  2. Another alternative is to render this as a page with the 2 vue instances as components inside a parent component. This setup enables the parent component to handle the state and pass it down to the child components. The primary advantage of this method is its simplicity in adding extra functionality.

In both scenarios, you would end up implementing something like this in the map:

map.on('click', e => emit('mapClick', e.feature));

Subsequently, in your component, listen for the mapClick either on the event bus if you opt for route 1 or in the parent container component if you choose route 2

I hope this explanation proves helpful. Best of luck!


Illustrative example of a Parent component where the sidepanel emits:

sidepanel = Vue.component('sidepanel')
map = Vue.component('map')

parentComponent = Vue.component('parent', {
  components: { map, sidepanel },
  template: `
    <div>
      <map @mapClick="handleMapClick" :dataAsProp="someData"></map>
      <sidepanel @userClicked="handleUserClick" :dataAsProp="someData"/>
    </div>
  `,
  data() {
    return { someData: [] }
  },
  methods: {
    handleMapClick(event, data) {
      // Handle your update here, save data, etc
    },
    handleUserClick(event, data) {
      // Handle your update here, save data, etc
    }
  }
})

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

Display different text based on the property value

I need to display different text based on the value of a property, showing "offline" if camera.key is null and "online" otherwise. Here's the template I'm using: <h3>Camera sensors</h3> <table> <th>Name</th> ...

The function .play() cannot be executed on document.getElementById(...) - it is not a

There is an error in the console indicating that document.getElementById(...).play is not a valid function. import React from 'react'; const musicComponent=(props)=>{ const style={background:props.color} return( <div classN ...

Bind AngularJS data to select elements

I am encountering an issue with data binding on a select tag, despite following the guidelines in the documentation. Here is my select element: <select id="start-type" ng-model="startType"> <option value="day-of-week">Day of the week</op ...

Using TypeScript to consolidate numerous interfaces into a single interface

I am seeking to streamline multiple interfaces into one cohesive interface called Member: interface Person { name?: { firstName?: string; lastName?: string; }; age: number; birthdate?: Date; } interface User { username: string; emai ...

Is it possible to program Zapier to automatically open a hyperlink that was included in an email?

Currently, I am utilizing Mailparser for extracting information from a booking email, and then leveraging Zapier to input this booking into our system. Within the email, there exists a link that needs to be accessed in order to confirm the booking. I am i ...

What is preventing me from using .bind(this) directly when declaring a function?

Consider the code snippet below: function x() { this.abc = 1; function f1() { alert(this.abc); }.bind(this) var f2 = function b() { alert(this.abc); }.bind(this); } I am curious about how to make the "this" of the out ...

Unique rephrased text: "Varied wrapping styles in both

Feeling frustrated with a seemingly commonplace issue. Despite the thousands of times it has been asked before, I can't seem to find an answer on Google. I wanted to neatly display my text within one of my cards, but so far I've only achieved th ...

I would like a div element to slide up from the bottom of the page

Could someone please assist me in creating a popup div that appears from bottom to top when a specific button is clicked? I would like the div to be fixed without affecting the overall page content. Any help would be greatly appreciated. Thank you! $( ...

Learn the process of directing to a view in a jQuery AJAX call with Spring MVC

Below is the ajax call I am using: $.ajax({ type: "POST", url: contextPath +"/action", cache:false, dataType: 'text', data: {Id:Id}, success: funct ...

Creating a custom loading spinner featuring your logo

Hello, I am looking to create a custom loading spinner using CSS, JS or any other method with my logo. I have the logo in PNG, GIF, and SVG formats and would like to use it for long site loads, image loads, or any other loading processes within my Vue3 pro ...

Is it possible to execute a specified quantity of Promises simultaneously in Nodejs?

Currently, I am working on developing a web scraping application that utilizes a REST API to gather information from multiple entities on the server. The core functionality of this application can be summarized as follows: let buffer = [] for(entity in ent ...

Discover how to generate nested dynamic routes in NextJS by linking to MongoDB data using the getStaticProps and getStaticPaths functions

Currently, I am facing a challenge with implementing dynamic paths in NextJS and I'm struggling to find a solution. Let me provide some context for better understanding. I am working on developing an ecommerce application using NextJS, and the folder ...

Unable to load the first tab in Material-ui V3 after fetching data or when the page loads

After using Material UI version 3 scrollable-tab and fetching data to load tabs and tab container, I encountered an issue where the first tab does not automatically load on page load. It requires a click in order to see the information. I have searched on ...

Send data using only Javascript

Hey there, I'm a beginner in javascript and I'm having some trouble submitting a form using pure javascript. Here is my code: var myform = document.getElementById('js-post-form'); myform.addEventListener('submit', function(e ...

Use the jQuery .GET() method two times to retrieve data and obtain the outcomes

My code involves making a series of GET calls where the returned data from one call is used in another call before returning the final results. However, I want to ensure that my program waits until all the data is retrieved. This is what I have come up wi ...

Verify the information received from the ajax call to PHP

After incorporating all the guidance I received, I performed an update and here are the results: UPDATED CODE: $(document).ready(function(){ $("#submit").submit(function(e){ e.preventDefault(); var username = $("#username").val(); var ...

Tips for evaluating the outputs of two computed properties in Vue.js

In our application, users can apply to events and we also have blog posts about various events. We want to display all the blog posts related to events that a user has applied to. Each post is associated with an eventId and each application object contain ...

Name the Angular interpolation function with the (click) event

I have a JSON file that defines different dynamic buttons, but when I click on them, the function is not being called. Here's how my JSON file looks: export const liveButtonData = [ { title: 'My Name', function: 'getName()'} ...

Initialize React Native project

Which ruby command shows the path to Ruby: /Users/User/.rbenv/shims/ruby Ruby -v command displays the version of Ruby installed: ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin21] Which bundle command reveals the path to Bundler: /Users/Us ...

What steps should I take to grant API access if cross-browser requests are restricted?

Creating a C# web service to retrieve data from a server raises the question of how to grant API access to other users who want to query it using client-side code. For example, imagine the web service is hosted on Domain1.com. How can someone from Domain2 ...