Vue 3 has a known issue where scoped styles do not get applied correctly within the content of a <slot> element

Utilizing the Oruga and Storybook libraries for creating Vue 3 components.

The code in the Vue file looks like this:

<template>
  <o-radio v-bind="$props" v-model="model">
    <slot />
  </o-radio>
</template>

<script lang="ts">
import { defineComponent } from "@vue/runtime-core";
import Radio from '../mixins/radio-mixins';

export default defineComponent({
  name: "BaseRadio",
  computed: {
    model: {
      get() {
        return this.$props.nativeValue;
      },
      set(value: any) {
        this.$emit("input", value);
      },
    },
  },
  emits: ["input"],
  props: {
    ...Radio.props,
  },
});
</script>

<style scoped>
  .b-radio.radio.is-primary .check:checked {
    border-color: var(--color-blue);
  }
  .b-radio.radio.is-primary .check:checked:focus {
    box-shadow: 0 0 3px 3px var(--color-light-blue);
  }
  .b-radio.radio.is-primary .check:before {
    background: var(--color-blue);
  }
</style>

Within the <style> tag, I am adjusting the classes provided by the Oruga library to achieve the desired styling.

The issue arises when using the scoped attribute in the <style> tag, causing none of the styles to be applied. Removing scoped allows the styles to work as intended.

Is there a way to resolve this problem? I need to apply these styles while still utilizing the scoped tag in the <style>.

Answer №1

Typically, slotted content (elements displayed with the help of the <slot> tag) remains unaffected by the scoped styles of the hosting component that contains that <slot>. Instead, that content is considered to be "owned by" its parent, which is the actual component being rendered into the <slot>.

This presents you with 3 potential options:

Embed the styles directly in the slotted component

If you include the styles within the component that is inserted into the slot, those styles will be applied to that component regardless of where it appears.

Of course, this may not always be practical or even feasible, especially if you do not have control over the content being slotted in.

Utilize the :slotted() Selector

The ::slotted() pseudo-class is specifically meant for referencing elements rendered inside a <slot> tag. Vue 3 has its own version of this feature, denoted as :slotted() (with a single colon : instead of two ::).

<style scoped>
  :slotted(.b-radio.radio.is-primary .check:checked) {
    border-color: var(--color-blue);
  }
  :slotted(.b-radio.radio.is-primary .check:checked:focus) {
    box-shadow: 0 0 3px 3px var(--color-light-blue);
  }
  :slotted(.b-radio.radio.is-primary .check:before) {
    background: var(--color-blue);
  }
</style>

Employ the :deep() Selector

While the scoped attribute confines styles to the component they belong to, the :deep() selector allows components to apply styles to their children, including slotted components since they are rendered as child nodes in the DOM.

<style scoped>
  :deep(.b-radio.radio.is-primary .check:checked) {
    border-color: var(--color-blue);
  }
  :deep(.b-radio.radio.is-primary .check:checked:focus) {
    box-shadow: 0 0 3px 3px var(--color-light-blue);
  }
  :deep(.b-radio.radio.is-primary .check:before) {
    background: var(--color-blue);
  }
</style>

However, it is worth noting that using this method could potentially extend the scope of styles down the hierarchy; grandchildren and beyond may still be influenced by these styles. Care should be taken with class names and selectors to prevent unexpected issues.

Answer №2

Perhaps the reason for this issue is that you are attempting to alter classes that are specific to the DOM due to the Oruga framework being used. By excluding the "scoped" property, you can make changes to Oruga classes globally. These Oruga classes only apply within the component itself and not in your actual code when working with the component.

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

Ways to showcase every resource from an API in React JS

I need help with adding code to display products along with their images from an API in my existing code. Can someone assist me with this? import React, {useState, useEffect} from 'react' import "bootstrap/dist/css/bootstrap.min.css" im ...

Is there a way to access comprehensive data pertaining to an ID through Ajax?

I need help with an Ajax call. Below is the code I currently have: $.ajax({ async: true, url: 'test/', type: 'POST', datatype: 'text json', data: { id: id, }, success: function(data) { // Retrieve the da ...

Verify the presence of a JSON object within the session storage using JavaScript

I'm currently developing a website where some data is stored within the session. In the initial page, I need to verify if the JSON object already exists in the session. Below is the code snippet that's causing issues: var passedTotal = JSON.par ...

Isn't AJAX all about the same origin policy?

Despite my confusion surrounding the same domain origin policy and jQuery AJAX, I have noticed that when I make a GET request to a URL using jQuery, I am able to successfully retrieve the results. This goes against what I understood about the restriction ...

Executing the outer function from within the inner function of a different outer function

Imagine this scenario: function firstFunction() { console.log("This is the first function") } secondFunction() { thirdFunction() { //call firstFunction inside thirdFunction } } What is the way to invoke firstFunction from thirdFunction? ...

Adjust the placement of image when changing the size of the window

Is there a way to prevent an image with a fixed position from covering up page content when the browser window is resized? <div > <img id="img1" class="wrapperImage"></img> </div> <style type="text/css"> .wrapperImag ...

What is the process for assigning default values to dynamically generated form elements?

I have been working on building a single-page application (SPA) using JavaScript and jQuery. During the process, I encountered an issue with a dynamic form. The user is able to add specific fields as needed, but if they don't generate and utilize all ...

Ways to avoid extra function loads in JavaScript

I'm currently working on an instant search feature and have some code implemented: $(function() { var timer; $("#searchterm").on('keypress',function() { timer && clearTimeout(timer); timer = setTimeout(doStuff, 800); tim ...

Issue with MUI Autocomplete not showing selected name on initial option selection

I encountered a strange issue with the Autocomplete component from Material UI. Here is the code snippet in question: const [isContactListInitialised, setContactListInitialised] = useState(false); const toggleContactListInitialized = () => { setContactL ...

Modify components in a directive template depending on the information in the scope

In my project, I am facing an issue with a directive nested within an ng-repeat. The ng-repeat item is passed to the directive and I am trying to generate a directive template or templateUrl with dynamic elements based on a key/value in the item. Specifica ...

Attempting to run the npm install command led to encountering a SyntaxError with an

Recently, I made some alterations to my npm configuration and ever since then, I have been consistently encountering the same error whenever I try to install various packages. It seems that due to a personal mistake in changing the npm settings, I am now u ...

Check if a value is present in the array with *ngIf

I'm curious about how to use the ngIf directive in a specific scenario. In my Angular application, I have dynamically generated angular material toggles, each with a unique id. I'm familiar with using ngIf to conditionally display elements on the ...

Incorporating traditional Javascript classes for modeling in React development

Can traditional JavaScript classes be utilized in models within the MVC framework while using React, as opposed to relying on Redux or contexts & reducers which may impact reusability? If this approach is feasible, how can we efficiently 'subscribe&ap ...

Troubleshooting a live chat box for CSS alignment issues

Need help with aligning a live chat box on every webpage? Check out this example for reference: You can find my code here: https://jsfiddle.net/fn77d0de/2/ ...

The state is failing to initiate a re-render despite a change in its state

In my React application, I have encountered an issue with combining two reducers. One of the reducers is functioning properly, but the other one is not triggering a re-render after a state change. Interestingly, when I save a document or make a change in t ...

Issue with handling keypress event and click event in Internet Explorer

Below is the HTML code for an input text box and a button: <div id="sender" onKeyUp="keypressed(event);"> Your message: <input type="text" name="msg" size="70" id="msg" /> <button onClick="doWork();">Send</button> </di ...

Reactivating a React hook following the execution of a function or within a function in ReactJS

A new react hooks function has been created to retrieve data from an API and display it on the page: function useJobs () { const [jobs, setJobs] = React.useState([]) const [locations, setLocations] = React.useState({}) const [departments, setDepartm ...

Using Javascript to dynamically add form fields based on the selection made in a combo box

I am in the process of creating an information submission page for a website, where various fields will need to be dynamically generated based on the selection made in a combo box. For example, if the user selects "2" from the combo box, then two addition ...

Placing additional items on discovered components within the mounted wrapper

My form has a selector reusable component structured like this: <template> <div class="channelDetail" data-test="channelDetail"> <div class="row"> <BaseTypography class="label">{{ ...

Leveraging the power of context to fetch data from a store in a React component within the Next

I'm having trouble with the title in my React project, and I'm new to React and Nextjs. When trying to fetch data from my dummy chat messages, I encountered this error: × TypeError: undefined is not iterable (cannot read property Symbol(Sy ...