What is the method for assigning classes to a Vue.js Functional Component from its parent component?

Imagine a scenario where I have a functional component:

<template functional>
    <div>Some functional component</div>
</template>

Now, when I render this component within a parent element with classes:

<parent>
    <some-child class="new-class"></some-child>
</parent>

The resulting DOM does not have the new-class applied to the Functional child component. Upon my understanding, the Vue-loader compiles the Functional component against the render function context, as explained here. This means that classes are not directly applied and merged intelligently.

So, the question arises - how can I ensure that the Functional component works well with externally applied classes when using a template?

Please note: I am aware that it is easily achievable through the render function:

Vue.component("functional-comp", {
    functional: true,
    render(h, context) {
        return h("div", context.data, "Some functional component");
    }
});

Answer №1

Summary:

To retrieve the class, use data.staticClass, and for other attributes, bind them with data.attrs

<template functional>
  <div class="my-class" :class="data.staticClass || ''" v-bind="data.attrs">
    //...
  </div>
</template>

Explanation:

While v-bind can bind most attributes like id or style, it cannot be used for class due to its reserved status in JavaScript. Therefore, Vue employs staticClass instead, requiring manual binding through :class="data.staticClass".

If the parent fails to define the staticClass property, one should handle this by using :class="data.staticClass || ''"

Illustration:

Unfortunately, a code snippet demonstration is not feasible due to the nature of functional components within *.vue files. However, a functioning example can be found on codesandbox: https://codesandbox.io/s/z64lm33vol

Answer №2

Here is an example of a render function inside a functional component, inspired by @Daniel's answer:

render(createElement, { data } {
  return createElement(
    'div',
    {
      class: {
        ...(data.staticClass && {
          [data.staticClass]: true,
        })
      },
      attrs: {
        ...data.attrs,
      }
    }
  )
}

In this code snippet, we are utilizing ES6 computed property names to assign a static class.

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

Gulp is ensuring the destination file remains unchanged

I'm encountering an issue with gulp in my project. I've set up a process to automate the compilation of source and styles into a single file using gulp. However, I'm facing a problem where it doesn't want to overwrite the `application.j ...

What steps should be taken to guarantee that the filter function is completed before making an Axios request, in order to avoid encountering an undefined variable error when working with Axios

Encountering an issue with an undefined variable while trying to stringify and parse a filtered array in the backend using axios. The error occurs sporadically on the live server, often triggered by a timeout function within the filter process. This resul ...

"Effortlessly emptying the text field with material-ui in React

I need assistance with clearing the content of two text fields and a button using Material-UI in React-JS. I am new to React and unsure how to achieve this. Below is the code I currently have: import React from 'react'; import RaisedButton from ...

Create a consistent number based on quantity

Looking to generate a sequence of numbers equal to the count in PHP or JavaScript for my application. For example, if my total count is 7: <?php $total = 7; I would like to generate seven 1's like this: $split_one = [1,1,1,1,1,1,1]; If my count ...

What are some ways I can utilize Babel in standalone mode to convert an HTML import into a variable declaration?

I am trying to utilize the Babel plugin babel-plugin-transform-html-import-to-string to dynamically transform my code in the browser client. However, the babel-plugin-transform-html-import-to-string is designed to run on node with file libraries, which are ...

Troubleshooting HTML/CSS and JavaScript Issues with Dropdown Menus

I'm having trouble getting my dropdown menu to work properly and I can't figure out why. The JavaScript code should toggle a class that hides the language options and slides up the other tabs like "Contact". However, when I click the button, noth ...

Tips for iterating through an associative array/object within a MongoDB schema instantiation using mongoose without the need to specify schema configuration parameters

I've been searching on Google for hours without finding a clear answer. Perhaps I need to adjust my search terms? Here's my question: I'm a beginner with MongoDB and I'm trying to modify the values of a schema instance before saving it ...

Synchronously retrieving JSON data from a URL using JavaScript

I'm currently working on extracting the title of a YouTube video using jQuery to parse JSON. The issue I am facing is that it works asynchronously, resulting in the answer being displayed after the page has already loaded. Here's the current resu ...

How to style the background color of the selected option in a <select> element using

Is there a specific style I can use to change the color of a selected option in a dropdown menu? For example: <HTML> <BODY> <FORM NAME="form1"> <SELECT NAME="mySelect" SIZE="7" style="background-color:red;"> <OPTION>Test 1 &l ...

Refresh the dropdown menu selection to the default option

My HTML dropdown menu includes a default option along with dynamically generated options using ng-options. The variable dropdown is bound to the dynamic options, not the default one. <td> <select ng-model="dropdown" ng-options="item as item.n ...

Need help figuring out how to use Javascript:void(0) to click a button in Selenium?

Struggling with finding the right solution, I have attempted various methods. Apologies for any formatting errors, but the element that requires clicking is: <button href="javascript:void(0)" id="payNewBeneficiary" class="button-new-payee"> ...

What is the process for creating a global variable in JavaScript?

Having trouble changing the value of "invocation_num" within a loop? I attempted to modify it as follows, but ended up with an undefined value. Any help would be greatly appreciated. $(document).on("click", '.favoret', function(){ document ...

Proper Structure for Node System (BASIC)

Overview Recently, I entered the world of Node.js and built some basic back end functionality. However, I realized that everything was clustered in one file (index.js) which led me to explore tutorials on using express router middleware and adapting a mod ...

Combining various API requests within a Vue component, which includes a for loop

I'm delving into the world of API chaining, specifically trying to link two different API calls within a 'notes' Vue component. My knowledge of promises is basic at best, but I'm eager to enhance my skills in this area. The initial API ...

Leverage Pinia store in Vue helper functions

I have been working on my Vue.js application and I am looking to implement some helper functions that will utilize a Pinia store within the app. These functions need to be accessible by multiple components. Should I define these helper functions directly ...

Unidentified variable in Angular Ajax function when accessed outside its scope

Currently, I am in the process of creating a ticket admin table. However, I am facing some challenges with exporting a variable outside of an ajax function. Here is my code: app.controller('bodyController',function($scope,$http,$sce){ $scope.ti ...

My Fullcalendar is displaying events for the upcoming month. How can I resolve this issue?

This is the start date for my event in the full calendar: start: new Date('2016', '02', '07', 00, 30) However, when loading the calendar, this event is displaying on March 7, 2016. How can I resolve this issue? ...

Guide on waiting for AWS assumeRole before proceeding with defining the module

I'm currently working on a module that needs to export functions and variables, but before it can do that, it must switch user roles. Here is the code snippet I've come up with. What I need is for the anonymous async function to execute first, an ...

Displaying a Jquery slider by clicking on links

I am interested in setting up a slider for two different forms. Specifically, I plan to have one form labeled Form 1 and another labeled Form 2 displayed as text. When users click on Form 1, a table containing the form will slide out from underneath the ...

Error encountered in Vue Cli 3 when running Npm Build: Callback already triggered

Everything was running smoothly until this unexpected error popped up. I can execute npm run serve without any issues, but npm run build is a different story. Below is the detailed error log: 0 info it worked if it ends with ok 1 verbose cli [ 1 verbose c ...