Harnessing the power of data within different components

In my setup, I have two vital components in play. The initial one is responsible for presenting a list of items, while the second dictates the design and layout of these items.

These items reside in an array located within the app.vue file. Here lies my predicament - how do I effectively utilize this array across both components? How can I extract elements from each item in the array to populate fields like titles? Furthermore, what approach should I take to iterate through all items within the array and showcase them collectively within the display component?

Answer №1

One way to accomplish this is by utilizing a for loop along with component props

For instance

Splitting into two files:

  1. Start with the Parent component, like FruitComponent.vue
<template>
    <fruit-list v-for:"fruitTitle in fruitsList" :title="fruitTitle"></fruit-list>
</template>
<script>
    export default{            
        data () {
            return {
                fruitsList: ["apple", "banana", "orange"]
        } 
    }
</script>
  1. Then, create the Child component, e.g. FruitItem.vue
<template>
    <h3>{{fruitTitle}}</h3>
</template>
<script>
    export default{            
        props: {fruitTitle : String}
    }
</script>

Alternatively, for simpler scenarios

(Recommended only for very small components where placing child component HTML directly into the parent's "template" attribute is acceptable. Consider creating a separate file for cleaner structure)

  1. Including the Parent component code
<div id="fruits-component">
  <ol>
    <fruits-list v-for="fruit in fruitsItems" :fruits-item="fruit"></fruits-list>
  </ol>
</div>
  1. Create the dynamic rendering Child component
Vue.component('fruits-list', {
  props: ['fruitsItem'],
  template: '<h3>{{fruitsItem.value}}</h3>'
});
  1. Add the child component to the fruits-component
new Vue({
  el: '#fruits-component',
  data: {
    fruitsItems: [
      {value: 'apple'},
      {value: 'orange'}
    ]
  }
});

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

Is reCAPTCHA v3 functioning properly?

My front end utilizes vuetify in this manner : validate: async function () { let tokenCaptcha await this.$recaptcha('login').then((token) => { tokenCaptcha = token }) if (this.$refs.form.validate() && tokenC ...

Launching a modal in a new browser window with the help of JavaScript or PHP

I need to implement a feature where clicking a link opens a modal in a new tab and redirects the current page to a different link, similar to how retailmenot handles coupons. Here is the code snippet I am currently working with: <div onClick="myFunctio ...

Oops! Looks like there was an error: $http is not defined

I'm facing a challenge with implementing $http in the AngularJS framework. I've gone through various other resources on this issue, but I can't seem to figure out what I'm doing incorrectly. Any assistance would be highly appreciated. T ...

What is the reason for Bower consistently choosing to download the Angular version 1.5.9-build.5086+sha...?

Struggling to manage my front end dependencies using bower.json. No matter how I specify the version of Angular in bower, a different version is downloaded every time. The issue is that many functionalities in my code rely on previous versions of Angular, ...

Discovering the array with the most elements among several arrays in PHP

Looking to compare multiple arrays and find the one with the highest number of items? Here's how: Let's say we have 3 arrays: $a_arr = array( '0' => '45', '1' => '50', '2' => '100& ...

The custom validation function in jQuery is not triggering

I am facing an issue with my HTML and JavaScript setup, which looks like this: <html> <head> <title>Validation Test</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script src="htt ...

What is the best way to distribute components between two NextJS projects?

Confused about the best way to share ReactJs components between two NextJs applications - one for e-commerce and the other for a manager portal. In the e-commerce app, there are various UI components that I want to reuse in the manager portal. Considering ...

Triggering a jQuery event when a CSS property is altered

My current approach involves utilizing the .animate method to shift a div 100px to the right in just 1 second. Essentially, this means moving by 1px every 10ms. I am now exploring whether there exists an event that could be triggered after each individual ...

Could someone please explain why my ajax is not functioning properly?

I have been working on an AJAX function to pass input values from one page to another. However, I am facing a challenge where the value is not being passed as expected after redirection. Despite my efforts, I cannot figure out why it's not functionin ...

When the button is clicked, send data using 'POST' method to the php file and fetch

<script> $(document).ready(function(){ $("#vE_rebtn").click(function{ var reverifyEmail = '<?php echo $_SESSION["verifyEmIPv"]; ?>'; $('#rE_rebtn').hide(); $('#re_ ...

The concept of recursively exporting modules in Node.js modules

Looking for a way to recursively export all .hbs files in a NodeJS 14+ project main JS. I attempted the following: module.exports = () => ({ partial : __dirname + "/../partial/**.hbs", helper : __dirname + "/../helper/*.js" } ...

Utilizing Laravel's whereJsonContains for JSON Where Clauses

I am encountering an issue with queries in Laravel. Below is the code snippet in Laravel: $table_data = \App\Models\Data::where('data_keys', 'element') ->whereJsonContains('data_values->trx_type', 'wi ...

Is it possible to have a hidden div box within a WordPress post that is only visible to the author of the

How can I create a div box with "id=secret" inside a post that is only visible to the author of the post? I initially made it for the admin, but now I want the id to be visible exclusively to the post's author. For instance: If the author is curren ...

Calculating values within dynamically generated elements requires utilizing JavaScript to target and extract the

I am working on creating input fields inside an HTML table using Vue.js. On click of a button, I want to perform some calculations based on the input values. However, it seems that the calculations are not happening as desired. What I have attempted so fa ...

How can you initiate the wizard sequence again in TelegrafJS?

I've created a handler function for "/start" that leads to the wizard scene. Now, I have a message with an inline_keyboard containing a button labeled "redo". When I click on the "redo" button, I want it to restart the entire scene, basically initiat ...

Issue with updating overall expenditure functionality

I'm currently in the process of developing a straightforward shopping cart with the help of simpleCart.js. Up until now, I've managed to successfully showcase items, add them to the basket, and proceed to checkout. However, my next challenge inv ...

Convert a Material UI component into a string representation

I've been tasked with using a tool that creates a terminal interface within the browser. Our goal is to display HTML content, including Material components. The tricky part is that the tool requires input as strings. I discovered a package called jsx- ...

How can I create a slot component with a prop defined in the child component?

If I have three components called Alpha, Bravo, and Charlie. Here is how they are structured: Alpha.vue <template> <div class="alpha"> <bravo> <template slot="card"> <charlie></cha ...

The step-by-step guide to deactivating server-side JavaScript on MongoDB using a Java application

I am working on a Java web application that interacts with a MongoDB Atlas database for CRUD operations. My goal is to disable server-side JavaScript for my Atlas instance directly from the Java web application itself. After researching, I came across th ...

Commitment failing to deliver the information

I am currently attempting to retrieve data based on a specific ObjectId using promises. The function is successfully fetching the data from the database, but it is failing to return the result as expected. Below is the code snippet: getScreenDetails = fun ...