Vue: Conditionally importing SCSS when a component is instantiated

My goal is to import Material SCSS exclusively for my Admin component.

While this setup works smoothly during local development, the issue arises when I deploy my site to Firebase hosting - the Material styles start affecting not just my Admin component, but all components in my SPA.

I have experimented with different approaches:

// Attempting to import the SCSS files within the Admin component ID
  #admin {
    @import "../../../../node_modules/vue-material/dist/vue-material.min.css";
    @import "../../../../node_modules/vue-material/dist/theme/default.css";
  }

then

// Trying to import the SCSS files within the Admin component CLASS
  .admin {
    @import "../../../../node_modules/vue-material/dist/vue-material.min.css";
    @import "../../../../node_modules/vue-material/dist/theme/default.css";
  }

Next, I attempted to include the imports directly inside the Admin component itself

// Importing the SCSS files within the Admin component's beforeCreate lifecycle hook
  beforeCreate() {
    // Ensuring style files are only loaded if this component is being used
    import("vue-material/dist/vue-material.min.css")
    import("vue-material/dist/theme/default.css")
  },

and finally:

// Adding the SCSS files within the Admin component, which is only rendered if the v-if condition in 
// the main App component evaluates to true.
<script>
.
.
.
import "vue-material/dist/vue-material.min.css"
import "vue-material/dist/theme/default.css"
.
.

I initially thought that browser caching might be causing the problem, but even after hard reloading Chrome and trying different browsers, the issue persisted.

Furthermore, commenting out the CSS imports and redeploying did resolve the issue. Therefore, it seems like there is an issue within the Admin component regarding how it imports and applies the styles.

Another puzzling aspect is that I included a console log in the created hook of the component to verify if it was being created unnecessarily, but it wasn't. This leads me to believe that the styles are somehow getting mixed into the build process with everything else.

I am certain that there is a straightforward solution to this problem, but I have exhausted my ideas.

Answer №1

After experimenting further, I discovered that the most effective method was to dynamically load styles from a CDN to the HEAD element once the component is created. Here is how I implemented it:

created() {
  this.inject_material_fonts_and_icons_into_header()
},
.
.
.
methods: {
inject_material_styles_into_header() {
  [
    "https://unpkg.com/vue-material@beta/dist/theme/default.css",
    "https://unpkg.com/vue-material@beta/dist/vue-material.min.css",
    "https://fonts.googleapis.com/css?family=Roboto:400,500,700,400italic|Material+Icons"
  ].forEach(route => {
    const link_el = document.createElement("link")

    link_el.setAttribute("rel", "stylesheet")
    link_el.setAttribute("href", route)

    document.head.appendChild(link_el);
  })
}
}

If you have any other recommendations, please feel free to share them. While I am not entirely satisfied with relying on CDNs, I currently do not have the luxury of spending more time on this particular issue.

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

When trying to implement appDir and withPWA in next.config.js, an error has been encountered

My next.config.js is set up with next-pwa and an experimental app feature included. const withPWA = require('next-pwa'); module.exports = withPWA({ pwa: { dest: 'public', disable: process.env.NODE_ENV === 'development&ap ...

Utilizing a custom component within the Vue ais-hits feature

I have been working on implementing an Algolia search page, and initially, everything was functioning correctly with the following code: <ais-hits> <template #default="{ items }"> … </template> </ais-hits> ...

Changes made in React are not reflected in the DOM

import React, { Component } from "react"; import ReactDOM from "react-dom"; import "./index.css"; class App extends Component { constructor(props) { super(props); this.state = { text: "", listItem: [] } this.onChangeInpu ...

How can we automatically redirect users to an external website based on their responses to a specific question in SurveyJS?

Within my SurveyJS json, I have a radiogroup question that prompts users to make a choice. If they select a specific option, I'd like to redirect them to a different page. Otherwise, I want them to continue with the survey. Is this achievable? (The s ...

Combining NodeJs with Mysql for multiple queries using a chained method

Hey everyone, I'm struggling with running mysql queries repeatedly in my Node.js application. I need to shape the second query based on the results of the first one. The code example I have below is not working as expected. Can anyone provide guidance ...

Attempting to create a redirection landing page

I have a process where I create a new user and save it in my database with the following code snippet: const newUser = new User({ username: userId, password: pass, nameOfUser: user_name, emailOfUser: user_email ); newUser.save(); res.redir ...

Local host's attempt to retrieve data from an external site via an Axios GET request was rejected

I'm currently attempting to execute a GET request on an external website in order to scrape some information. Unfortunately, my axios GET request is returning a connection error. I suspect that this issue may be related to the fact that I am sending t ...

Trigger a jQuery event when an element is moved to a new line

Is there a way to trigger a jQuery event when an element moves to a new line in the view? I want to hide navigation items and run additional JavaScript code when this happens. Any ideas on how to achieve this? Here's how my navigation appears in a wi ...

Events related to key press timing in HTML 5 canvas

Currently, I am developing a game similar to Stick Hero for Android using HTML5. I am working on the code that will capture the time of key press (specifically the right arrow key with ASCII 39) in JavaScript and expand a stick accordingly. <!doctype h ...

Modify the CSS style of the select label and change the color of the currently selected option in MUI

For the past few days, I've been facing challenges with implementing MUI components while working on a page for a React app. I'm almost finished with my project, but there are 2 key things missing... On my page, I have utilized a Select and an ...

Add an event to your Fullcalendar with a date that is not the same as the present date in your MySQL database

I currently have Fullcalendar set up to display events from a MySQL table (title + datetime) and allow users to add new events by clicking on a specific day within the calendar. However, I am facing an issue where it only adds events to the current day ev ...

Angular 6: Dealing with Type Errors in the HttpClient Request

I am encountering issues with my services. I am attempting to retrieve a list of media files (generated by NodeJS, which generates a JSON file containing all media items). Although I can successfully fetch the data, I am facing an error stating "Property & ...

When using the `display: table-cell` property on a div element, it does not automatically respect

How can I restrict the width of columns by defining a width attribute on the div.dcolumn DOM element to preserve the layout with overflowing cells? I want the content of any overflowing cell (like the 9px column) to be hidden while maintaining the specifie ...

Blend express router by chaining the (.route) method with other HTTP methods like (.get, .post, etc) to create

Here is my code structure: let router = require( 'express' ).Router(); Later on, I define my routes like this: router .route( '/' ) .get( listMiddleware ); router .route( '/:id' ) .get( getOneByIdMiddleware ...

How can I utilize jQuery to save a simple text string in a mySQL database?

Seeking guidance on this jQuery code snippet: $('.bggallery_images').click(function () { var newBG = "url('" + $(this).attr('src'); var fullpath = $(this).attr('src'); var filename = fullpath.replace('im ...

Tips for preventing multiple clicks when posting AJAX requests in jQuery

Using Django, I was able to create a website and implement a voting page with jQuery AJAX. The code works perfectly fine as shown below: <!doctype html> <html> <head> <script src="jquery-1.10.2.min.js"></script> <met ...

Is ng-repeat failing to bind values in the Dom?

When loading data dynamically to ng-repeat, I am encountering an issue where the data is not binding to ul. Typically, this can happen with duplicate indexes, but in my case I'm unsure of what's causing it. Any suggestions? main.html <div> ...

Can an onload function be triggered within the location.href command?

Can a function be called onload in the location.href using jQuery? location.href = getContextPath() + "/home/returnSeachResult?search=" + $('#id-search-text-box').val() + "&category=" + $('#search_concept').text() + "onload='j ...

Only validate the nested object if the parent object is already present

In my scenario, I have a request body structured as follows: { "folder": { "value": "testFolder", "operator": "=" }, "name": { "value": "5456", "operator": "contains" } } While the presence of the request body is optional, I want to ensure that b ...

Switching the URL without reloading the page in NEXT.JS

Currently, I am in the process of building an ecommerce store using NEXT.JS and Redux. Within the product listing page, I have incorporated a sorting select dropdown featuring options such as Price Low to High, Price High to Low, and New Arrivals. My goal ...