How can Vue JS 3 components exchange data between each other?

I am attempting to share data from a variable favorite_count in the Favorites component located in the file Favorites.vue. My goal is to pass this data to the App Component in the App.vue file but I have been unsuccessful so far. I want any changes made to the value of favorite_count in the Favorites component to also reflect in the App Component. Despite conducting thorough research online, I have not found a solution yet. Any suggestions on what could be causing the issue?

Favorites.vue file

<template>
    <div class="row m-5">
        <h3 class="col-8">Your Favorites</h3>
        <div class="col-4">
            <p class="pull-right m-1">Picks 
            <span >{{ favorite_count }}</span>  / 5</p>
        </div>
        <hr>
    </div>
</template>
<script>
export default {
    name: 'favorites',
    data() {
        return {
            favorite_count: 5,
        }
    },
    methods: {
        changeFavoriteCount() { 
            this.favorite_count = this.favorite_count + 2;
        },
        emitToParent (event) {
          this.$emit('childToParent', this.favorite_count)
        }
    }
}
</script>

App.vue file

<template>
    <div class="navbar navbar-expand-md navbar-dark bg-primary">
        <div class="collapse navbar-collapse" id="navbarResponsive">
            <ul class="navbar-nav"> 
                <li class="nav-item">
                    <router-link to="/favorites" class="btn btn-info">
                      Favorites ( {{ favorite_count }} )
                    </router-link>
                </li>
            </ul>
        </div>
    </div> 
</template>
<script> 
import Favorites from './components/Favorites.vue'
 
export default {
  name: 'App',
  components: {
    Favorites
  },
  data () {
    return { 
      favorite_count: 0, 
    }
  }
}
</script>

Answer №1

Incorporating <router-view> into your application at a later stage requires careful consideration. I recommend checking out this solution

If you plan on embedding Favorites within <template> in App.vue, utilizing props is advised:

1. Define the 'shared' variable in the parent component (App.vue)

data () {
  return { 
    favorite_count: 0, 
  }
},

2. Specify props in the child component (Favorites.vue)

export default {
  props: { favorite_count: Number },
  ...
}

3. Pass favorite_count as a prop to Favorites

<template>
  ...
    <Favorites :favorite_count="favorite_count" ... />
</template>

To update favorite_count, emit an event to the parent component. For further details, refer to the Vue docs

Edit: To clarify, if you intend to modify favorite_count from Favorites.vue, emitting an event to App.vue is necessary to prevent prop mutation.

This entails relocating the changeFavoriteCount() function to App.vue and setting up a listener in the child component to execute this function:

// App.vue
<template>
  ...
    <Favorites 
       @your-update-event="changeFavoriteCount" 
       :favorite_count="favorite_count" ...
    />
</template>

...

changeFavoriteCount(newVal) { 
    this.favorite_count = newVal;
},

Answer №2

modify your Favourite.vue file with the following changes

<template>
  <div class="row m-5">
    <h3 class="col-8">Your Top Choices</h3>
    <div class="col-4">
      <p class="pull-right m-1">
        Selections <span>{{ favorite_count }}</span> / 5

        <button @click="changeFavoriteCount"gt;Update preferred_count</button>
      </p>
    </div>
    <hr />
  </div>
</template>
<script>
export default {
  name: "topFavorites",
  data() {
    return {
      favorite_count: 5,
    };
  },
  methods: {
    changeFavoriteCount() {
      this.favorite_count = this.favorite_count + 2;
      this.emitToParent();
    },
    emitToParent() {
      this.$emit("childToParent", this.favorite_count);
    },
  },
};
</script>

adjust the App.vue file as shown below

<template>
    <div class="navbar navbar-expand-md navbar-dark bg-primary">
        <div class="collapse navbar-collapse" id="navbarResponsive">
            <ul class="navbar-nav"> 
                <li class="nav-item">
                    <router-link to="/favorites" class="btn btn-info">
                      
                      <Top Favorites @childToParent="updateFavorite" />
                      Top Choices ( {{ favorite_count }} )
                    </router-link>
                </li>
            </ul>
        </div>
    </div> 
</template>
<script> 
import TopFavorites from './components/TopFavorites.vue'
 
export default {
  name: 'App',
  components: {
    TopFavorites
  },
  data () {
    return { 
      favorite_count: 0, 
    }
  },
  methods: {
    updateFavorite(data) {
      this.favorite_count = data;
    },
  },
}
</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

Enhancing Numbers with JavaScript

What I'm Looking for: I have 5 counters on my webpage, each starting at 0 and counting upwards to different set values at varying speeds. For example, if I input the values of 10, 25, 1500, 400, and 500 in my variables, I want all counters to reach t ...

The function "Jest spyOn" does not exist

I’m currently facing an unfamiliar error while testing my React component using Jest. Here’s the code snippet for my <Row/> component: In my Row component, there are various methods like showDetailsPanel(), handleStatusChange(), handleModalCanc ...

Animating a background image to slide in from the bottom to the top using CSS transition

Here is a link to a codepen example: https://codepen.io/jon424/pen/XWzGNLe The current effect in this example involves covering an image with a white square, moving from top to bottom when the "toggle" button is clicked. I am interested in reversing this ...

Email replay feature

Having an issue with my email validation function. I found the code I'm using here: Repeat email in HTML Form not the same. Why? The problem I am facing is that if you incorrectly enter your email in the first input "eMail" and correctly in the seco ...

How to properly Open a "div" Element by its ID in ReactJS

Today, I want to share an issue that I've been facing. To simplify things, I have mapped a BDD, The result of this mapping is displayed in multiple cards, There's a button that when clicked opens up more details on the map, But here's wh ...

Issue with a Jquery toggleClass function not working properly on hover

Hello everyone! I am a newbie in the community and relatively new to the world of web programming. I am encountering an issue that is really frustrating me. I attempted to use this code to add a class when hovering over the ul list element so that I can d ...

Ajax: client dilemma created by the interaction of two functions

My university homework assignment requires me to develop a small e-commerce website. After logging in, the user will be directed to the homepage where they will receive a JSON object from the server containing product information to dynamically generate th ...

Unable to access path for children through buttons in parent path

As a data scientist entering the world of frontend development, I find myself faced with the task of creating a UI at the request of my boss. Please bear with me as I attempt to explain my issue in layman's terms. Currently, I am using Vue.js and hav ...

Issue with form action redirection on Node JS Express server not functioning correctly

My EJS application involves using jQuery in the JavaScript code to fetch JSON data from the Google Custom Search API. The app then uses the GET method to navigate to /search, passing the query as the attribute for q. Here's an example of the form&apos ...

Is there a way for ResponsiveSlides to fade the pager without causing any disruption to the content below, all

I have been working with the Responsive Slides jQuery plugin and made some custom modifications. Everything is going smoothly, but I am facing an issue with getting the pager and next/prev controls to fade in when hovering over the container. Although I s ...

Reveal and conceal information with a customized web address

I have a PHP and MySQL blog that I want to display in a div using show and hide JavaScript functions. Everything works fine with other divs, but the issue arises when clicking on a vanity URL causing my webpage to refresh every time it's clicked. The ...

Problem arising from animation not commencing at expected starting point

Creating a feature on an app that involves breathing exercises using CSS animations. The challenge I'm facing is ensuring the words "exhale" and "inhale" appear synchronously with the animation of a circle shrinking and enlarging. However, the animati ...

Guide to automatically updating a table with AJAX requests

My task involves utilizing AJAX to request a random string consisting of 10 numbers from an asp page. The numbers must be delimited by "||" and displayed in a table format. The table is designed to showcase only the top 10 results, with each new row addin ...

Clicking on the image "Nav" will load the div into the designated target and set its display to none. The div will

Can someone help me with loading a div into a target from an onclick using image navigation? I also need to hide the inactive divs, ensuring that only the 1st div is initially loaded when the page loads. I've tried searching for a solution but haven&a ...

Nuxt frequently experiencing crashes at short intervals

Since updating to Nuxt version 2.12.2, I've been encountering this issue intermittently every few minutes. The timing seems sporadic, but it persists consistently. The only solution so far has been to restart the server. events.js:287 throw er; ...

Tips for fixing the async/await problem in JavaScript

Here is the code I've been working on: let icsFileData = []; icsFileData = filterAttachmentArray.map(async(file) => { let buff = new Buffer(file.data, 'base64'); let text = buff.toString('ascii'); const data = await ical ...

Are there any drawbacks to converting all instance methods into arrow functions in order to prevent binding loss?

What are the potential drawbacks of converting all instance methods into arrow functions to avoid the "lost binding" issue? For example, when using ReactJS, the statement onClick={this.foo} can lead to lost binding, as it translates to createElement({ ... ...

Tips on changing the outline color by clicking

I'm working on a simple code where I need to change the outline color when a user clicks on a text field. <input type="text" id="box1" /> <input type="password" id="box2" /> <input type="email" id="box3" /> <input type="submit" ...

Manipulating variables across various methods in TypeScript

I have a simple code snippet where two variables are defined in the Main method and I need to access them from another method. However, I am encountering an issue with 'variables are not defined', even though I specified them in the declerations ...

What steps do I need to take to modify the MUI Badge component and insert custom text inside?

Is there a way to replace the number with a label next to a new row added to my table using MUI Badge? For example, instead of displaying a number like 4, I want it to show the word "New" as shown in this image: enter image description here This is the co ...