How can I retrieve the attributes of multiple identical components within a webpage?

I've recently delved into learning Vue and decided to create a small application for adding fractions together. I have developed two main components: Fraction.vue and App.vue. The App.vue component contains multiple instances of the Fraction component.

Here is the code for Fraction.vue:

export default {
  data() {
    return {
      numerator: 0,
      denominator: 1
   };
 },
 computed: {
   result() {
     return (this.numerator / this.denominator).toFixed(2);
   }
 }
};

And here is the code for App.vue:

 <template>
  <div class="content">
    <div class="fractions">
      <Fraction v-for="fraction in fractions" :key="fraction">
        <span v-if="fractions.indexOf(fraction) === fractions.length - 1">
          =
        </span>
        <span v-else>+</span>
      </Fraction>
      <div class="result">
        <span>{{ result }}</span>
      </div>
    </div>
    <div class="add-fraction">
      <button @click="addFraction">Add fraction</button>
    </div>
  </div>
</template>

<script>
import Fraction from "./Fraction";
export default {
  components: {
    Fraction: Fraction
  },
  data() {
    return {
      fractions: [1, 2]
    };
  },
  methods: {
    addFraction() {
      if (this.fractions.length !== 5) {
        this.fractions.push(this.getRandomInt(1, 100));
      } else {
        alert("The maximum number of fractions in the expression is 5.");
      }
    },
    getRandomInt(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min)) + min;
    }
  },
  computed: {
    result() {
      return 213;
    }
  }
};
</script>

I'm struggling with obtaining the final result of the equation.

Answer №1

It seems like the issue here lies in your approach, as you may not have fully grasped how Vue functions. To focus more on practical coding rather than explanations, I have simplified your example to make my point clearer.

Fraction.vue

// In this component, you can display information
// Each component can have its own template
<template>
  <div>
    {{ result }}
  </div>

</template>
export default {
  props: {
    numerator: Number,
    denominator: Number
  },
  computed: {
    result() {
      return (this.numerator / this.denominator).toFixed(2);
    }
  }
};

App.vue

<template>
  <div class="content">
    <div class="fractions">
      //<!-- Here is the simplest way to pass values to a component -->
      <Fraction 
        v-for="(fraction, index) in fractions" 
        :key="index" 
        :numerator="fraction.numerator"
        :denominator="fraction.denominator"/>
    </div>
  </div>
</template>

<script>
import Fraction from "./Fraction";
export default {
  components: {
    Fraction: Fraction
  },
  data() {
    return {
      // Arrays can contain nested anonymous objects
      fractions: [
        {
          numerator: 1,
          denominator: 2
        },
        {
          numerator: 2,
          denominator: 1
        },  
      ]
    };
  },
};
</script>

If your goal is to create reusable code components, using mixins would be more appropriate than components.

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

Retrieve information in JSON format from a document

I'm trying to extract data from a JSON file without knowing the exact location of the data. Here is an example JSON: var names= [ { "category":"category1" , "name1":"david", "name2":"jhon", "name3":"peter" }, { "category":"catego ...

Limiting the usage of a command in Discord.js to one user at a time, rather than all users

I'm in the process of developing a discord.js bot and I need to implement a cooldown for a specific command. After searching several tutorials online, I found that most of them apply the cooldown to all commands (meaning all users have to wait a set ...

Real-time Property Availability Widget

I need assistance with creating a website for a homeowner who wants to rent out their property. The client requires a feature that allows them to log in and easily mark individual days as available or unavailable for rental by choosing specific colors for ...

What steps can I take to direct mobile visitors to the mobile-friendly version of my website?

Looking for a way to automatically redirect users on mobile devices from www.domain.com to the new mobile version at m.domain.com? ...

Protractor quickly launches and closes the Chrome browser without completing the entire scenario

In order to test my application using protractor, I created a scenario. The application begins with a non-angular login page and then progresses to an angular page after logging in. Here is the javascript code snippet that was utilized: var chai = requir ...

Endless Google Locations Instances

My database entries are being displayed in a table using input fields. I want the Location field for each entry to be automatically completed using Google's API. HTML: <input name="edit_airplane[1][location]" type="text" class="airplane_location" ...

My socket io connection is not working. There seems to be an issue with the connection io

After initiating my server, I am able to see the console.log message showing that the server is running on the specified port. However, I am not receiving the console.log message indicating a successful socket io connection with a unique socket id. import ...

Leveraging URL parameters within node.js and Express

Having no prior experience with node, I decided to delve into the Express project in VS2019. My goal was to create master/detail pages with a MongoDB data source. In my pursuit, I configured three routes in /routes/index.js. //The following route works as ...

What strategies can I implement to ensure my modal dialog box remains responsive? Adjusting the window size causes the modal box to malfunction and lose its structure

Whenever I adjust the size of the browser window, the elements inside the modal box become misaligned. HTML <div class='modal'> <div class='modal-content'> </div> </div> Below is the CSS for the modal ...

Strange CSS/browser storage glitch

UPDATE: JUST REALIZED THIS ISSUE IS ONLY OCCURRING ON FIREFOX, NOT CHROME ANOTHER UPDATE: Oddly enough, this problem only occurs locally. When I push it to GitHub, everything works fine. So strange. I suppose that means it's not a major issue. On my ...

Missing pieces of data | Utilizing React and Redux Toolkit

I'm facing a problem that's keeping me up for almost 24 hours. I just finished coding this slice, but when I submit the data, only the automatically generated ID is returned. Let me explain further - I have a skill component with two input forms ...

Is it possible for npm to assist in determining the appropriate version of Primeng that is compatible with Angular 16 dependencies

While trying to add primeng to my project, I ran into an error message: npm i primeng npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

What is the best way to include a class with Knockout JS?

After going through the basic Knockout tutorial and examining various examples, I decided to try it out myself on jsFiddle. However, I encountered some issues as my attempts did not quite work. The goal is simple - I just want to add the class open to a d ...

JQuery - Triggering mouseenter/hover event only on top-level menu items, excluding the nested submenu items (list items that are not within nested lists)

I have a complex navigation menu structure with nested lists, and I'm struggling to trigger an event only on the top-level items when hovered. Despite trying different jQuery selectors and methods, such as using the NOT selector or targeting direct ch ...

Angular is known for sending only the fields that have changed to the update method

I need help with optimizing my save method. When a user clicks SAVE, I only want to send the fields that have been changed instead of all 50+ fields on the page. This will reduce the amount of data being sent every time. Api.Admin.update({ obsoleteDat ...

Adjust the size of the iframe image to fit seamlessly within the design

Is there a way to adjust the size of the image on the right without altering the layout design? The current GIF is 500x500px, but it is only displaying as 100x100px. Any assistance would be greatly appreciated! To see what I currently have (Demo with code ...

Failing to send contact information using JSON in PHP

I attempted to transmit JSON data to PHP for email processing, but encountered an issue where the process veered into the 'else' condition during debugging. Here is the code snippet: HTML <form id="cbp-mc-form" class="cbp-mc-form" method="po ...

What is the best way to output information to a webpage using json_encode in PHP?

I've implemented a button on my webpage that triggers a database call using ajax, so the page can dynamically display the data without requiring a refresh. Oddly, when I click the button and inspect the source and network tab, everything seems to be f ...

"Enhance user experience with the React Popover feature from Material UI

Looking for help on creating a dynamic color palette with a hover feature for the PaletteIcon. The issue I'm facing is that when I try to select a color, the palette disappears. Is there a specific property I should add to the React component or anoth ...

When using res.json(), the data is returned as res.data. However, trying to access the _id property within it will result

I'm facing a challenge in comprehending why when I make a res.json call in my application, it successfully sends data (an order object). However, when I attempt to access and assign a specific piece of that data (res.data._id) into a variable, it retu ...