Tips for connecting two separate Vue.js applications

Take note: this is the rid function that is called within the code.

<script>
        const rid = () => "rid_" + Array.from(crypto.getRandomValues(new BigUint64Array(2))).map(item => item.toString(36)).join("");
</script>

I am utilizing vue.js from CDN in an HTML file and also assigning Ids to <app> elements using jquery, as shown below:

<app>
</app>
<script>
(function() {
        const app_rid = rid()
        $("app").last().attr("id", app_rid)
        createApp({}).mount("#"+app_rid)
});
</script>

In my code, I have two applications structured like this:

<!-- #app 1 -->
<app>
</app>
<script>
(function() {
        const app_rid = rid()
        $("app").last().attr("id", app_rid)
        createApp({}).mount("#"+app_rid)
});
</script>

<!-- app #2 -->
<app>
</app>
<script>
(function() {
        const app_rid = rid()
        $("app").last().attr("id", app_rid)
        createApp({}).mount("#"+app_rid)
});
</script>

The goal is to be able to call a method of app #1 from app #2 or any other potential apps like app #3, app #4, etc., in the future.

What app #1 does in my code is render bootstrap toasts, represented by the following code:

<component name="toast" class="visually-hidden">
        <div class="toast show" role="alert" aria-live="assertive" aria-atomic="true">
                <div class="toast-header">
                        <i class="bi me-2" :class="[icon,'text-'+color]"></i>
                        <strong class="me-auto" :class="['text-'+color]">{{title}}</strong>
                        <small class="me-2">{{time}}</small>
                        <button type="button" class="btn btn-link text-danger-emphasis bi bi-x p-0" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
                <div class="toast-body">{{message}}</div>
        </div>
</component>
<app>
        <div class="toast-container position-fixed bottom-0 end-0 p-3">
                <toast-component 
                        v-for="(toast, index) in toasts" 
                        :key="index" 
                        :color="toast.color"
                        :icon="toast.icon"
                        :title="toast.title" 
                        :time="toast.time" 
                        :message="toast.message"
                />
        </div>
</app>
...

The objective is to invoke the AddToast() method of this app from other apps.

Answer №1

After some experimenting, I uncovered a new method to accomplish this task. By declaring the createApp app #1 as a public variable, I was able to access its methods more easily. Here is how I made the initial change:

<app>
</app>
<script>
let app1;
(function() {
        const app_rid = rid()
        $("app").last().attr("id", app_rid)
        app1 = createApp({
                methods: {
                        Example() {
                        }
                }
        }).mount("#"+app_rid)
});
</script>

With this setup, calling the methods became simpler:

app1.Example();

I also realized that I could streamline the app id definition with this code:

$("app").last().attr("id", rid())
createApp({}).mount("#"+$("app").last().attr("id"))

This approach eliminates the need for defining functions anonymously.

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

How can I stop a hyperlink from activating Jquery?

A script was created to highlight any <TR> element when a user clicks on it, and it is functioning correctly. <script> $(document).ready(function () { $(document).on('click', 'tbody tr', function (e) { ...

What is the best way to prepopulate form values in a Vue object?

Sharing my code snippet: HTML: <div id="user-panel"> <div class="text-center"> {{ fillItem }} </div> <form method="POST" action="http://site5/user_account/experiences/17" accept-charset="UTF-8" v-on:s ...

Exploring the Ref feature in Vue's Composition API

How do I correctly type my Ref firstName as a string? There are two errors highlighted, one in the template - {{ firstName }}, and the other in the script - const firstName = ref('') as String. I believe the issue lies in the typing, as I assume ...

What is the best way to simultaneously check two conditions in Vue.js?

In my current scenario, I am facing a challenge with checking both conditions simultaneously. If an attachment exists in the request but the attachment field does not exist in the form, it should display a message in the modal. Similarly, if body text exis ...

I am encountering difficulties displaying the image and CSS files from another folder in my HTML with Node.js

I am facing difficulty in establishing a connection between my front-end and back-end using node.js. As a result, the website only displays the HTML code without linking to the CSS or image files. Here is the folder structure: root -src •pi ...

A Guide to Dynamically Updating Page Titles Using JavaScript in a Ruby on Rails Application

Every time I use Ajax to load a blog post on the webpage, I adjust the <title> to "My Blog - BLOGPOST_TITLE". It is worth mentioning that "My Blog - " also shows up in the application layout. My dilemma is, how do I inform my Javascript about the " ...

Use the spread operator to assign a value to the keyname

Would it be possible to dynamically assign key names to the spread operator? For instance, consider the following: 'first, second, third'.split(','); // Array(3) : [ 'first', 'second', 'third' ] I would ...

Service in Angular2+ that broadcasts notifications to multiple components and aggregates results for evaluation

My objective is to develop a service that, when invoked, triggers an event and waits for subscribers to return data. Once all subscribers have responded to the event, the component that initiated the service call can proceed with their feedback. I explore ...

Javascript: Troubleshooting Unexpected Variable Behavior in HTML Code

My issue is as follows: I am attempting to retrieve text from a JSON file in my HTML. In the header of my HTML, I have linked a tag with the following code: var language = ""; var langDoc = null; //Function to change the value function setLang() { v ...

Establishing the httppostedfilebase variable when validation is unsuccessful in an ASP.Net MVC view

I'm currently facing an issue with handling validation errors in my application. I have implemented uploading and downloading images successfully, but when there are validation errors and the controller redirects back to the page, the HttpPostedFileBa ...

What could be causing my HTML to not display properly after making changes to a text node?

Can a DOM text node be altered in such a way: node.nodeValue = "foo <strong> bar </strong>" so that it displays the HTML correctly? Appreciate any help. ...

Unable to retrieve data from SpringBoot controller using $http.get request

I have developed an application that will execute queries on my store's database based on user input on the webpage. The backend method is functioning correctly and returns the response, but I am having trouble displaying the data in a dynamic table o ...

Discovering an item within an array of objects using the find method in Ajax

Within my backend PHP code, I iteratively define the following: foreach ( $data as $res ){ $approved[ ] = [ 'id' => $count, 'title' => "some title" ]; $count++;$title=... ) This eventually leads to the creation ...

Having trouble confirming signature with Node.js Crypto library, specifically with key pairs

I have a concise nodejs code snippet where I attempt to sign a string and then verify it using node crypto along with key pairs generated through openssl. Despite trying various methods, the result consistently shows "false" indicating that the signature c ...

How can you make a Tempory Drawer wider in Material Components Web?

Increasing the Width of a Temporary Drawer in Material-components-web Greetings! I am currently facing an issue with Material-components-web In the provided demo here, I would like to extend the width of the Temporary drawer to accommodate additional co ...

Develop a dynamic modal feature that allows users to input SQL queries and execute them seamlessly without having to

I need to implement a feature in my web application where users can set the price of an item displayed in an HTML table that is populated from a MySQL database. When a user clicks on a button next to a row, a modal should open with a text input field and a ...

Update the HTML table by changing the first cell in the first row to span multiple

I currently have a table structured like this: <table> <thead> <tr> <th></th> <th>Col1</th> <th>Col2</th> <th>Col3</th> <th>Col4& ...

Is there a way to automatically update a webpage?

When two computers, pc1 and pc2, are on the same page and pc1 changes the status of a field, is there a way to update pc2's aspx page without needing to refresh it? ...

What is the best way to confine a child div with a dynamic height?

Upon initialization of Jwplayer, a class is injected with the following CSS: .jwplayer.jw-flag-aspect-mode { height: auto !important; } Here's my code snippet: <div style="height: 80vh; width: 100%"> <div style="height: 90%; width: 100 ...

What is preventing me from passing a JSON array as data in a GET request using jQuery Ajax?

When sending a get request like the one below: $.ajax({ url: 'http://localhost:8000/api/points/', contentType:"application/json", dataType: "json", data: JSON.stringify({"content_type":content_type,"object_id":object_id}), t ...