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

Ways to divide and extract information stored within an array

I need help printing out this array of data. Here is how my data is structured: [[["Not Critical","Not Critical"]],[["Not Critical","Not Critical"]],[["Not Critical","Not Critical"]]] This is how I want the data to be displayed (each innermost value on ...

Creating a function to update data in a Node.js/MongoDB environment

Hey there! I'm new to working with nodejs and mongodb, and I'm trying to create a function that updates the win, lose, and draw record in my UserSchema. Here's my Schema: UserSchema = new mongoose.Schema({ username:'string', ...

Determine the number of rows in an Ajax-fed datatable (including paginated rows) that have a specific value in a

I am struggling with counting rows in #datatableOne where the 'Status' column has a value of 'Unknown'. I have attempted a couple of solutions, but they are not giving me the desired results. The first solution only counts the rows on ...

Denied running the inline script in Redocly

Experimenting with redoc-cli (https://github.com/Redocly/redoc/) in order to generate static documentation. Unfortunately, encountered some stumbling blocks due to errors related to the Content-Security-Policy, which seems to be blocking JavaScript code ex ...

Having difficulty accessing `props` in a React JS and Next JS application

Currently, I am developing a React application that utilizes Server Side Rendering. In this project, I am using React Js and Next Js as my primary framework. My goal is to retrieve initial props using the getServerSideProps method by consulting the documen ...

Utilizing variable values in Google Charts with AngularJS

Hello everyone, I am attempting to display a chart using data obtained from an API. The output of the API is in the form of List<String> and not in JSON format. Here is the snippet of my JS file: google.load('visualization', '1', ...

What is the best way to obtain the value of a Promise within a function?

When working with Promises, accessing the value inside the .then method is simple. Take a look at this example: const Promise = require("bluebird"); const fs = Promise.promisifyAll(require('fs')); const mergeValues = require('./helper' ...

No information available at the moment

When the data is not present, it displays as "display none"... However, I want it to show "no data found" This is the current code if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].styl ...

What is the best way to access the second item using getByRole in React Testing Library when there is no specific name?

I am familiar with using the name option to select the first item here, but how can I go about selecting the second item if it does not have a name identified? -------------------------------------------------- button: Enter "Go": ...

Tips for extracting Stripe response post payment using a client-side-only integration

My current component handles sending a payment order to my stripe account on the client-side. Everything seems to be working fine, but I'm struggling to find a way to retrieve the response or token from stripe containing the order details, which I nee ...

Exploring JSON data hierarchies with AngularJS using ng-options

In my web app, I am utilizing AngularJS to create two dropdown lists using ng-options. The first dropdown displays a list of countries The second dropdown provides language preferences for the selected country As I am still new to AngularJS, I am able t ...

If the user fails to respond, Alexa will show an error message indicating that the skill response was marked as a failure

After completing the code for my Alexa skill, I encountered a problem. My fact-based skill template is set to wait for responses after the output, but if Alexa doesn't hear a response within 8 seconds, it generates an error (Skill response was marked ...

The function is malfunctioning following the alert

I am experiencing an issue with my renumbering list function. I have a delete button on the list that triggers a confirmation alert, but after the alert is shown, the renumbering function stops working. Here is my script: <script type="text/javascript ...

Challenges in Ensuring Proper Alignment of Connection Line Between Boxes on Left and Right Sides within a React Component

Currently, I am developing a React component that displays two sets of boxes on the left and right sides of the screen. Users can choose one box from each side and click a "Connect" button to draw a line between them. However, I am encountering an issue wh ...

Sentry platform is failing to record network-related problems

Incorporating Sentry into my Next.JS application has allowed me to easily detect JavaScript errors such as reference or syntax issues on the Sentry platform. Unfortunately, I have encountered some challenges as Sentry is not logging any network-related er ...

The validation of radio input signals results in an error being returned

For a while now, I've been trying to solve the issue with radio button validation in my current project. Surprisingly, it works fine when there are no other functions in the form besides the radio buttons themselves. I suspect that the problem lies wi ...

Creating a multi-tiered cascading menu in a web form: Harnessing the power of

In my form, there is a field called 'Protein Change' that includes a multi-level dropdown. Currently, when a user selects an option from the dropdown (for example, CNV->Deletion), the selection should be shown in the field. However, this funct ...

Step-by-step guide: Assigning a color to a card element in MaterializeCSS

I am currently working on a project using Vue.js where I want to display colored cards from MaterializeCSS. The colors are stored as hex codes in a separate database and are part of items looped through with the v-for loop, like this: <div ...

Unexpectedly, the NodeJS application experiences a crash following numerous requests

I can't seem to figure out why my Nodejs app crashes after a certain number of requests (currently 22). The issue arises with this simple get request handler: router.get('/api/docs/fetch', async (req,res) => { try{ let docs = ...

Using Vue.js to showcase a data table in either a grid or list view

Currently, I am diving into the world of vue.js while also sharpening my skills in javascript. My goal is to showcase a data table in list view and show folder images in grid view. However, I'm struggling with making it happen. Any guidance or assista ...