Why is there only one element in the slot when using v-for?

Within my Vue application code, there is a swiper component. Inside this component, I am using a v-for and a slot.

I am facing an issue in the parent component (Foo) where I need to access the component (baz) I inserted into the slot using a ref. However, it only returns a single element instead of an array as I expected.

Is there a way to maintain this structure of components and still receive the array I was anticipating? Is it even possible?

import Vue from "vue";

Vue.config.productionTip = false;

const Foo = {
  template: `
    <div>
    <swiper :items="items">
    <baz ref="baz"/>
    </swiper>
    </div>
  `,
  data: function() {
    return {
      items: [1, 2, 3, 4, 5]
    };
  },
  mounted: function() {
    this.$nextTick().then(() => {
      console.log({ refs: this.$refs.baz });
    });
  }
};

const Baz = { template: "<div>im baz</div>" };

const Swiper = {
  template: `
    <div class="swiper">
    <div v-for="(item, i) in items" :key="i">
        <slot></slot>
    </div>
    </div>
    `,
  props: ["items"]
};


Vue.component("foo", Foo);
Vue.component("baz", Baz);
Vue.component("swiper", Swiper);

new Vue({
  render: h => h(Foo)
}).$mount("#app");
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>

Answer №1

In order to achieve the desired outcome, it is recommended to modify your layout. Instead of implementing the v-for directive within the swiper template, consider utilizing it in the foo template. Allow the swiper template to focus solely on rendering a single item. To see this concept in action, refer to the following example: https://codesandbox.io/s/jolly-meninsky-qqe6k

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

Enhance the appearance of the activated header - Ionic 3 / Angular 5

On the current page, I want to emphasize the title by underlining it or changing its color - something that clearly indicates to the user which page they are on. Currently, I am utilizing lazy loading for navigating between pages, using modules for each pa ...

What is the best way to send multiple requests for the same file and retrieve the necessary response in PHP using jQuery AJAX?

var postID = $post->ID; $.ajax({ type: "POST", url: "<?php echo get_template_directory_uri();?>/b.php", data:{postID:postID}, dataType: 'json', success: function(re ...

Having Trouble Finding Vue Component Definition Using Vite Alias in Import Path

When I click on the Component within the code snippet: import Component from '@/components/Component.vue'; I am unable to navigate to its definition when using vite alias. Seeking a potential solution. ...

OBJLoader encountered an unexpected line: "<!DOCTYPE html>" while using vue cli3

Utilizing the vue-3d-model component for a 3D object viewer in cli3 has presented a challenge that needs to be addressed. <script> // import { ModelThree } from 'vue-3d-model' import { ModelObj } from 'vue-3d-model' ...

Creating scrollable Material tabs

In my application, I am utilizing Material tabs (using mat-tab elements inside a mat-tab-group). When there are too many tabs to be displayed at once, two navigation buttons appear to allow access to the other tabs: https://i.sstatic.net/i7Vhh.png I am l ...

Issue encountered with client.query function not functioning properly within the node.js node-postgres library

Currently, I am in the process of learning how to utilize the node-postgres package within node.js and express to establish a connection with a postgres server. Despite my efforts, the code I've written seems to have issues when it comes to executing ...

Achieving the perfect alignment: Centering a paragraph containing an image using JQuery

I need help centering the background image of my <p> tag on the webpage. Script $(function() { $('ul.nav a').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ ...

Nested iteration using a for loop in Javascript

I am attempting to iterate through a large array of values and calculate the average of one of the values for each second. I seem to be having trouble getting this code to function correctly, and it appears that the issue lies within the nested while loop. ...

When using $.getJSON, the callback function fails to execute

The Issue: The callback function in my $.getJSON request is not executing. When the page loads, nothing is displayed in the console or on the page. However, when the function is manually entered into the console, it works as expected. Here is the jQuery ...

How can one achieve a fading effect on the background using THREE.js?

I am attempting to achieve a fading effect on the drawing buffer while leaving trails of drawn objects, rather than clearing it every frame. It's a relatively simple effect that can be achieved in 2D using this code snippet: http://jsfiddle.net/faRW3/ ...

Performing the multiplication of two numbers stored in an object using AngularJS and then calculating the sum

I am currently facing a minor issue with multiplying numbers within an object in AngularJS. My goal is to refactor the code that multiplies two numbers directly in the HTML using AngularJS into a service or factory. Below is the existing code featuring the ...

Examining Resolver Functionality within NestJS

Today I am diving into the world of writing tests for NestJs resolvers. I have already written tests for my services, but now it's time to tackle testing resolvers. However, I realized that there is a lack of documentation on testing resolvers in the ...

Having trouble installing handlebars on Node using the command line

I've been attempting to integrate handlebars with node using the instructions from my book. The guide advised me to install handlebars like so: npm install --save express3-handlebar. However, this resulted in an error npm WARN deprecated express3-han ...

HTTP AJAX request automatically switching to HTTPS

Currently, I am facing an issue with making an AJAX POST request from a Chrome extension to my AWS app. The request is defined over http instead of https. I have made sure to incorporate the necessary CORS headers in my AWS app as seen below: app.use(func ...

Is it beneficial to combine Cypress and Jest in my testing strategy?

As I dive into learning Jest and Cypress simultaneously, I've come to realize they're not direct competitors - with Cypress focused on E2E testing and Jest on unit testing. Currently, I have integrated both tools into my project with a few tests. ...

Ways to retrieve the highest date value in an array

I'm running into an issue where I am trying to find the maximum day in an array of dates, but for some reason it keeps returning either Invalid Date or null. I'm not sure what's going wrong. Do you think I should convert the values to a diff ...

Using Jquery to target an element within the same DOM element and apply changes

My website platform doesn't assign any IDs or classes to the menus it generates, and uses nested lists for submenus. To make the submenus expand upon clicking, I created a jQuery script: $(function () { $(".wrapper ul li").click(function () { ...

Utilize the return value within a .map function following the completion of a request.get call

Essentially, for security reasons, I need to convert an image from a URL to base64. Currently, I have two functions in place. One function is responsible for converting the image from the URL to base64, and the other function is iterating over the databas ...

The map displayed on google.com appears different from the one featured on our website

The integration of the JS for the Google map on our website is working smoothly without any issues. However, when I zoom into our address on google.com/maps, our Hotel is listed as "Hotel". On the map displayed on our website, there are only a few entries ...

Troubleshooting jQuery Div Separation Problem

Currently, I am working on implementing resizable sidebars using jQuery and potentially jQueryUI. However, I am encountering an issue with the resizing functionality. Specifically, the right sidebar is causing some trouble in terms of proper resizing, wher ...