Vue - Utilizing child slots in the render method

Within my component, I am working with a default slot and attempting to enhance the layout by wrapping each item in the slot within a div. However, I am facing an issue where I need to retrieve the classes of one of the slot elements, but the VNode element does not have elm or $el available during runtime as it remains undefined.

Here is an example of the parent component template structure:

<Parent>
   <span>child 1</span>
   <p class="push">child 2</p>
   <Child>child 3</Child>
</Parent>

The desired rendered output should look like this:

<Parent>
   <Wrapper>
      <span>child 1</span>
   </Wrapper>
   <Wrapper class="push">
      <p>child 2</p>
   </Wrapper>
   <Wrapper>
      <Child>child 3</Child>
   </Wrapper>
</Parent>

Currently, my render function successfully wraps each element, however, I am struggling to access the classes within the slot children during rendering.

render(createElement) {
    const childs = [];
    this.$slots.default.forEach(item => {
      if (item.tag) {
        console.log(item.elm, item.componentInstance); // both returns undefined
        childs.push(createElement("Wrapper", [item]));
      }
    });

    return createElement(this.tag, { class: this.classes }, childs);
  }

So, how can I effectively access the classes of the slot elements within the render function?

Answer №1

To access the static class, you can utilize the data.staticClass attribute:

Vue.component("Child", {
  template: `
    <div>
      <slot />
    </div>
  `
})
Vue.component("Wrapper", {
  template: `
  <div>
    <slot />
  </div>
  `
})
Vue.component("Parent", {
  data() {
    return {
      tag: 'div'
    }
  },
  render(createElement) {
    const children = [];
    this.$slots.default.forEach(item => {
      if (item.tag) {
        let wrapperClasses = null
        if (item?.data?.staticClass) {
          // Extracting the static class and preserving it
          wrapperClasses = item.data.staticClass

          // Setting the static class to null on the original item
          item.data.staticClass = null
        }
        children.push(createElement(
          "Wrapper", {
            class: wrapperClasses
          }, [item]
        ));
      }
    });
    return createElement(this.tag, children);
  }
})
new Vue({
  el: "#app",
  template: `
    <div>
      <Parent>
        <span class="pull">child 1</span>
        <p class="push">child 2</p>
        <Child>child 3</Child>
      </Parent>
    </div>
  `
})
.push {
  color: red;
}

.pull {
  color: green;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7107041431435f475f4045">[email protected]</a>/dist/vue.js"></script>
<div id="app"></div>

  • You can view the classes in the console for verification.

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

Having trouble looping through an array of objects containing images in Javascript?

I am currently facing challenges with iterating through an array of objects that contain images. The array appears empty when logged in the console, but upon inspecting it in the console, I can see all the objects along with their iteration numbers. I have ...

Steps for creating a sleek vertical slider with transitional effects using JavaScript and HTML

Take a look at my code snippet: <table> <tr> <td onclick="shownav()">Equations of Circle <div id="myDownnav" class="sidenav"> <a>General Info</a> <a>In Pola ...

SignalR's postback interrupts the functionality of jQuery actions

On my screen, I have a widget that updates data and changes its class based on server-side interactions. It also responds to mouse clicks. To notify multiple clients of updates simultaneously, I'm using SignalR. The problem arises when I wrap everythi ...

Perform a task upon clicking the JavaScript menu

Implementing dropdown menu items using a text link with JavaScript and CSS. You can view a demo here. I am looking to trigger an action when each menu item is clicked. Currently, they are not behaving as expected. HTML: <span class="inline-dropdown- ...

Determine if a certain value is present in a JSON data structure

Exploring the depths of NodeJS, I am utilizing a JSON Object for user validation. JSON content (users.json): { "users": [{ "fname": "Robert", "lname": "Downey Jr.", "password": "ironman" }, { "fname": "Chris", ...

What is the best way to handle asynchronous requests in frontend development with Nuxt.js?

Recently delving into Vue and Nuxt, I have been grappling with a query surrounding asynchronous requests. My understanding so far is that utilizing asyncData along with axios in Nuxt allows for fetching data that can be showcased on the frontend. However, ...

Create a parent dropdown class that contains two separate bootstrap dropdowns nested within it

I am encountering an issue with my dropdown menus. I have 2 dropdown menu items under the same parent dropdown class. However, when I click on dropdown action 1, it displays the body of dropdown menu 2 items instead. <!DOCTYPE html> <html> < ...

Dealing with issues escaping unicode characters in JavaScript

Whenever I need to load data from an external file based on a specific event, I make use of the following jQuery code: $("#container").load("/include/data.php?name=" + escape(name)); An issue arises when the JavaScript variable "name" contains Unicode ch ...

What is the procedure for updating or adding data to a JSON file with angularJS?

After successfully creating a local JSON file and retrieving data from it using app.controller('appCtrl', function($scope, $http){ $http.get('employees.json').success(function(data){ $scope.employees=angular.fromJson(data.employee ...

Exporting a module with Node.js is a crucial aspect of building

Within my custom module, I have successfully set up an export function. module.exports = function(callback) { var request = require("request") var url = "http://sheetsu.com/apis/94dc0db4" request({ url: url, json: true }, ...

Collaborative Desktop & Web Application powered by Javascript REST/Ajax

Currently, my node.js back-end is seamlessly working with a web-based JavaScript client by sending AJAX requests. However, I am now contemplating creating a compact desktop version of the JavaScript client using solely JavaScript, specifically leveraging ...

What are the repercussions of labeling a function, TypeScript interface, or TypeScript type with export but never actually importing it? Is this considered poor practice or is there a potential consequence?

I find myself grappling with a seemingly straightforward question that surprisingly has not been asked before by others. I am currently immersed in a TypeScript project involving Vue, and one of the developers has taken to labeling numerous interfaces and ...

How does the functionality of $.ajax differ from that of $.get?

Similar Inquiry: Understanding the Variations of $.ajax(), $.get(), and $.load() I'm curious about the disparities between $.get() and $.ajax The given code showcases calls like this: $.get(href) .success(function (content) { $(&apos ...

Struggling to access specific data within a JSON object? Wondering how to extract and display data from a JSON object in VUE?

Despite my extensive searching on Stack and the internet, I have not been able to find a solution to my problem. Currently, I am attempting to retrieve data from a JSON file located in the Vue src folder. The file contains three arrays with names that inc ...

Instructions on inserting a new row beneath a selected row using jQuery

https://i.stack.imgur.com/AlwHm.png When the second column is clicked, the method below is called: function getListOfList(primaryId, isFlat, col) { alert(primaryId) $.ajax({ url : ("/" + serverURL + "/dataGrid/getChilds"), ...

When trying to access data within objects using JSON iteration, it may lead to encountering an issue of reading a

Attempting to retrieve specific data from a JSON file obtained from a website has proven challenging. While iterating through the collection of objects, undefined values are constantly encountered. Unfortunately, if the JSON is poorly structured, modificat ...

Guide on implementing two submission options in an HTML form using JavaScript

Currently, I am working on a form that includes two buttons for saving inputted data to different locations. However, I am facing an issue with the functionality of the form when it comes to submitting the data. Since only one submit function can be activa ...

What is the process for redirecting an API response to Next.js 13?

Previously, I successfully piped the response of another API call to a Next.js API response like this: export default async function (req, res) { // prevent same site/ obfuscate original API // some logic here fetch(req.body.url).then(r => ...

In JavaScript, the gallery feature with Lightbox effect creates a unique touch as only half of the screen fades to black in

Hello everyone, I'm a complete beginner when it comes to programming so please be gentle with me on my first question :) I'm trying to put together a simple website with a lightbox gallery, and you can check out what I have so far here. The prob ...

Ways to prompt a specific text value to generate varied responses

Whenever I try to input the letter "h", I expect a specific value in return but for some reason, it's not working as intended. Despite my best efforts to troubleshoot the issue, I have been unsuccessful in finding a solution. It's frustrating bec ...