Changing the data of a child component that is passed through slots from a parent component in Vue.js

Exploring the world of components is new to me, and I'm currently trying to understand how the parent-child relationship works in components. I have come across component libraries that define parent-child components, such as tables and table rows:

<my-table>                <!-- Parent -->
    <my-tr>   </my-tr>    <!-- Child  -->
</my-table>

From what I gather, the child components interact with the parent components through slots. So the parent component should be defined like this:

<template>
    <div>
       <slot></slot>
    </div>
</template>

The parent element can then have multiple <my-tr> components, and the slot should render all of them. However, I am attempting something a bit more complex.

I am working on creating a slider using a similar approach. The slider consists of a my-slider component with my-slider-item components defined within it. I aim to control the visibility of these child components by modifying their properties.

The structure should look like this:

<my-slider>
    <my-slider-item>Item 1</my-slider-item>
    <my-slider-item>Item 2</my-slider-item>
    <my-slider-item>Item 3</my-slider-item>
</my-slider>

my-slider component

<template>
    <div class="my-slider">
        <slot></slot>
    </div>
</template>

my-slider-item component

<template>
    <div class="my-slider__item">
        <slot></slot>
    </div>
</template>

Now, my challenge lies in determining the number of <my-slider-item> components defined in the parent slot so that I can control the visibility of one child at a time to create the slider effect. Despite reviewing numerous examples, I seem to be missing a basic concept. I would greatly appreciate any assistance. Thank you!

Answer №1

Establishing the parent-child relationship involves importing the child component into the parent component and including it in the parent's 'components' option.

To illustrate this concept, I have created a simple scenario with Parent and Child component definitions, demonstrating a standard relationship implementation using Vue 2 and the Vue CLI.

ParentComponent.vue (parent)

<template>
  <div class="parent-component">
    <h4>Parent Component</h4>
    <child-component v-for="(item, index) in childItems" :key="index" :childItem="item" />
  </div>
</template>

<script>
  import ChildComponent from './ChildComponent.vue'

  export default {
    components: {
      ChildComponent
    },
    data() {
      return {
        childItems: [
          {
            name: 'Child Item 1'
          },
          {
            name: 'Child Item 2'
          },
          {
            name: 'Child Item 3'
          }
        ]
      }
    }
  }
</script>

ChildComponent.vue (child)

<template>
  <div class="child-component">
    <h5>{{ childItem.name }}</h5>
  </div>
</template>

<script>
  export default {
    props: {
      childItem: {
        type: Object,
        required: true
      }
    }
  }
</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

What could be causing me to receive two builds when using Webpack?

I am trying to capture the hash of the build by using a callback function in webpack: const compiler = webpack(webpackConfig, function (err, stats) { debug("Hash", stats.hash) }) However, I am encountering an issue where two builds are generated and on ...

Adjust rankings based on the number of upvotes received by a project

I'm facing a challenge with ranking projects based on the number of votes they receive. No matter the vote count, the project always ends up getting ranked as 1. To address this issue, I developed a function to manage the rank count and a return hand ...

Having trouble with the JSON format within the 'operations' field in the formData of your Next.js application?

I encountered a mutation that looks like this- mutation signUp($avatar: Upload!) { signUp( avatar: $avatar input: { name: "Siam Ahnaf" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

Looking for assistance with a JavaScript code snippet

I have encountered an issue while iterating through receipts in the given code snippet. The objective is to fetch the receipt number for each receipt and add it to a JSON object. However, I am facing a problem where the same receipt is appearing in two sep ...

What is the best method for linking an HTML file to CSS, javascript, and image files?

I need assistance with running an HTML file along with its source files that I downloaded from the server. The HTML file is located in NSCachesDirectory and here is the code snippet I am using. Can someone please help me figure this out? NSArray *paths ...

Basic AngularJS framework with minimal external dependencies

I have been searching for an AngularJS skeleton to set up my project, but it seems like all the skeletons I find online require the installation of numerous dependencies through npm and/or bower. Due to security concerns at the firm where I am working on ...

Guide to Embedding StencilJS components in a Storybook React Application

I am currently in the process of integrating Stencil and Storybook within the same project. While following this setup guide and this one, I encountered a step that requires publishing the component library to NPM, which is not my desired approach. In my ...

When utilizing the map function to render an array of objects, React encounters an error

My React application is throwing an error when using the map function. Interestingly, the code works fine in a sandbox environment. Error: ENOSPC: System limit for number of file watchers reached, watch. After creating a new React project, the error dis ...

What is the best way to send extra parameters to an ajax callback function?

Currently, I am implementing an ajax call in the following manner: util.AjaxCall(url, successCallbackFunction, errorCallbackFunction); function successCallbackFunction(result) { // Result returned from Ajax } Although everything is functioning correc ...

Updating Angular view based on service parameter change

In-depth Inquiry I have a specific setup with a header view and a main view in my Angular application. The goal is to include a "back" button in the header that should only be visible based on the current page I'm viewing. Actions Taken In my app ...

Leveraging nodemailer for automated email delivery

Hey there! I'm looking for some advice on how to set up scheduling with emailing using nodemailer. Ideally, I'd love to be able to schedule emails to send every day at 9am within a web app using nodemailer. However, I'm not sure where to st ...

Selecting a single checkbox automatically selects all other checkboxes

Is there a way to automatically check all other checkboxes if one checkbox is checked? Here's the code snippet I have: <tr> <td class="small"><asp:CheckBox ID="chkReportModuleName" runat="server" name="report"></asp:CheckBox& ...

Error in ThreeJS: The constructor THREE.FaceNormalsHelper is not defined

I am currently studying a course on three.js and encountered an issue in Chrome version 79 while progressing through the material: "THREE.FaceNormalsHelper is not a constructor". The line causing trouble is as follows: normals = new THREE.FaceNormalsH ...

Loading indicator displayed at the top of a div using JavaScript/jQuery

My current challenge involves implementing a progress bar, similar to the pace.js progress bar. The issue arises when the browser is refreshed, as the pace.js progress bar loads on top of the body instead of within a specified div. It is important that the ...

Tips for aligning actions to the right of a Vue3 Quasar horizontal card

Looking for help on getting the actions aligned to the far right side while keeping a small title using Quasar classes or Flexbox. When I try replacing the text on the right, it shifts the actions over which is not what I want. https://i.sstatic.net/nECR3 ...

Sending data from PHP to JavaScript using JSON encoding through POST requests

I am dealing with a multi-dimensional array that needs to be passed to a PHP script using JavaScript to parse JSON data and display it on Google Maps. I am experimenting with using forms to achieve this: <?php $jsontest = array( 0 => array( ...

Ways to extract a value from an HTML form in ASP.NET when using Html.EnumDropDownListFor

I am a beginner in ASP.NET and I recently set up a form that allows input from a C# enum: <form method="get"> <div class="form-group"> <label>Select Type:</label> @Html.EnumDropDownListFor(x = ...

Struggling to make fadeIn() function properly in conjunction with addClass

I've been struggling with this issue for quite some time now and I just can't seem to make it work. The JavaScript I'm working on involves using addClass and removeClass to display and hide a submenu element. While the addclass and removeCla ...

Utilize a single WebAssembly instance within two separate Web Workers

After compiling a wasm file from golang (version 1.3.5), I noticed that certain functions using goroutines are not supported. When these functions are called, they run in the current thread and slow down my worker significantly. To address this issue, I w ...

Utilize titles and hrefs for images in an array of objects

In my Canvas, there is a map as the background image with markers placed in different cities. These markers are images duplicated from an Array of Objects and added to the Canvas using drawImage(). Now, I need to include href and title attributes in these ...