Leverage variables from different Vue components and link them together

I'm currently working on two different sections of the website

First: Is it acceptable to use one instance within another, particularly with v-model? Are there any drawbacks to this approach?

Second: Is there a way to reference each other, such as placing the footer in the aside section even if one is declared before the other? When I attempt to do this, I receive an error stating "footer is undefined".

Here is my JavaScript code:

var aside = new Vue({
    "el": "aside",
    data: {
        name: "Peylan"
    }
});
var footer = new Vue({
    "el": "footer",
    data: {
        companyname: "Company Inc"
    }
});

This is my HTML code:

<aside><h3 v-bind="footer.companyname"></h3></aside>
<footer>
    <input type="text" v-model="aside.name">
</footer>

Answer №1

If you want to handle this situation properly, the best approach is to utilize a shared Vuex store.

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>

<aside><h3 v-text="footer.companyname"></h3></aside>
<footer>
    <input type="text" v-model="aside.name">
</footer>

<script>
const store = new Vuex.Store({
    strict: false,
    state: {
        aside: {
            name:"Peylan"
        },
        footer: {
            companyname:"Company Inc"
        }
    }
});
var aside = new Vue({
    store,
    "el":"aside",
    data:{},
    computed: {
        ...Vuex.mapState(['aside', 'footer'])
    }
});
var footer= new Vue({
    store,
    "el":"footer",
    data:{},
    computed: {
        ...Vuex.mapState(['aside', 'footer'])
    }
});
</script>

This demonstration provides a simplified demonstration. For more intricate usage (such as with getters, actions, and mutations), it is advisable to refer to Vuex's official documentation.


Alternatively, you could implement a computed property on both components, as shown below.

Keep in mind that this approach may introduce some challenges, which is why .$mount() is necessary in this scenario.

<script src="https://unpkg.com/vue"></script>

<aside><h3 v-text="footer.companyname"></h3>
</aside>
<footer>
    <input type="text" v-model="aside.name">
</footer>

<script>
var aside = new Vue({
    data:{
        name:"Peylan"
    },
    computed: {
        footer() { return footer; }
    }
});
var footer = new Vue({
    data:{
        companyname:"Company Inc"
    },
    computed: {
        aside() { return aside; }
    }
});
aside.$mount("aside");
footer.$mount("footer");
</script>

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 a unique button and apply a strike-through effect specifically for that individual list item

I've encountered an issue with my code that is causing problems specifically with nested LI elements under the targeted li element: $('#comment-section .comment-box a#un-do').hide(); $('#comment-section ul li[data-is-archived="true"]& ...

Gatsby causing issues with Material UI v5 server side rendering CSS arrangement

I shared my problem on this GitHub issue too: https://github.com/mui-org/material-ui/issues/25312 Currently, I'm working with the Gatsby example provided in Material UI v5: https://github.com/mui-org/material-ui/tree/next/examples/gatsby After imple ...

Is it possible to trigger a function using an event on "Any specified selector within a provided array"?

Trying to figure out how to show/hide a group of divs with different IDs by executing a function after creating an array of IDs for the NavBar. I'm having trouble getting started, but here's what I was thinking: $.each(array1, function(i, value) ...

React-navigation installation in React Native project failed due to ENOENT error - file or directory does not exist

Encountering errors during the installation of react-navigation in my react native project using npm install @react-navigation/native https://i.sstatic.net/uKiPQ.png The installation process reaches halfway, pauses for a few minutes, and then displays an ...

Adding code snippets to VueJS components

Is it possible to manually pull scripts and insert them into VueJS components, such as pulling Bootstrap CDN or other external JS scripts and inserting them directly? Thank you for your help! ...

Error with JavaScript callback functions

After creating a POST route, I encountered unexpected behavior in the code below. The message variable does not display the expected output. app.post("/", function (req, res, error) { var message = ""; tableSvc.createTable("tableName", function (error ...

Sorting complex strings in Typescript based on the dates contained within them

How can I sort a list of 2 strings with dates inside them so that the earlier one always comes first? The date is always after the second comma. For example, const example = ["AAA,5,2020-09-17T21:14:09.0545516Z", "AAA,0,2020-09-03T20:38:08. ...

Tips for resolving issues related to Nodemailer configuration

I am currently working on a script that sends form data to an email address. I am using Express and Nodemailer with Node.js, but as a beginner, I am struggling to understand why the email authorization stops and prevents the letters from being sent. Here ...

Different techniques to access values in a JSON array without relying on specific index positions

After making a request to an API, I received a JSON array with various attributes. One of the attributes is "State" and my task is to extract all the "EventName"(s) where State: "PR". The user will select the state from a dropdown menu. In order to achiev ...

Downloading PDF files on IOS while using Angular often results in the PDF opening in the same

I'm currently utilizing file-saver within my Angular application to retrieve a PDF generated from the backend. The library functions smoothly on desktop and Android devices, but I'm encountering issues with downloading files on iOS. Contrary to w ...

Is it possible to retrieve only the attributes in an array?

https://i.sstatic.net/E1DMb.png I am working with an array that has properties embedded within it. I am wondering if there is a method to separate out these properties from the array data and transform them into a distinct object containing only the prope ...

If the input is marked as checked, apply a class to the corresponding HTML element

I need to manipulate the .form-group class by adding it if the nearest hotelObj element is checked, and removing it when hotelObj is unchecked. Instead of using addClass(), I prefer to utilize css(). $(".form-group").click(function() { if ($(this).ch ...

When the mouse drags across the empty space, the force graph continually jumps

I have some questions. I utilized a force graph and added zoom functionality to it. However, when I drag the mouse over the blank area, the force graph keeps jumping erratically. like this Is there a way to prevent the graph from jumping? Thank you. ( ...

What causes an infinite loop in my app when passing a prop, and why doesn't it update the prop as expected?

Trying to pass a single variable from one component to another should be simple, but it's turning out to be more complicated than expected. I have a Search bar in one component and I want the input from that search bar to display in another component. ...

Nested loops in JavaScript can be combined with promises to efficiently handle

I am facing a challenge in looping through an array that contains another array as one of the parameters. My goal is to iterate through this nested array according to specific requirements, and then execute a function once the parent loop is finished. Can ...

Is it possible to attach a click handler to a ref?

Currently utilizing a 3rd party package and looking to include a minor interaction. Within the package, there is a button labeled as "next". Is there a method to incorporate a click handler for this specific reference? ...

Guide on how to retrieve a value using image.onload on the client side

I have encountered an issue with exporting a png image from an svg element using Blob. The problem arises when clicking the anchor tag to export the image, as the content is not rendered due to the asynchronous method (image.onload()) being called after th ...

Ways to implement CSS with javascript

I'm using PHP to retrieve data from my database and then leveraging Javascript to enable users to add it. However, I am facing challenges in making a div change its background color and apply borders. <div class="displayedItems"></div> &l ...

Displaying default value in select dropdown using v-model

I am working on a Vue selectbox with an initial v-model value, and I want to display its value on the selectbox. However, I am unsure of how to accomplish this. Any assistance would be greatly appreciated. new Vue({ el: "#demo", data() { return ...

Tips for updating a React state while using the history API

In an effort to simplify and stay focused on the problem, I recently wrote a brief piece of code. Within this code, there is a component containing a Dialog that plays a role in a commercial process. This Dialog allows users to input information such as no ...