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

Retrieve the student ID from the URL parameters and display all records with the matching ID

I am trying to display all rows with the same id using $_GET['student_id'], but I am encountering an error with Datatables. Here is my code. When I get the id from the URL, for example: example.com/example.php?=2222 All rows with the id 2222 wil ...

Navigating through elements in the hidden shadow DOM

Can elements within the Shadow DOM be accessed using python-selenium? For example: There is an input field with type="date": <input type="date" name="bday"> I want to click on the date picker button located on the right and select a ...

PlateJS: Transforming HTML into data

Trying to implement a functionality where clicking on a button retrieves an HTML string. The objective is to have this rich text editor within React-Hook-Form, and upon form submission, the value will be saved as HTML for database storage. Below is the pr ...

Best practices for positioning content within a Vuetify component?

I want to modify the position of these transparent buttons in this image: The current alignment of the buttons - Home, Offers, About and Contact - is at the top. How can I align them to the bottom of the image instead? Below is the code snippet I am usin ...

What could be causing my selenium tests to fail on travis-ci even though there have been no code changes, when they are passing successfully

I'm facing a tough challenge trying to troubleshoot a selenium test that passes when run locally but not on travis. Reviewing the travis build logs, I noticed that the test was passing in build #311 but started failing at build #312. It seems like th ...

Unable to access filteredItems from custom popup in uib-typeahead retrieval process

Issue with Retrieving Filtered Items from ng-repeat in Controller using $scope Despite trying to fetch filtered items from ng-repeat, the value of $scope.filteredItems appears as undefined when I log it to the console. I attempted to implement the solutio ...

Discover the final index of an array with Angular's ng-repeat functionality

I'm currently working with an Object that contains array values which I am trying to iterate over. Here's a simplified example of what I have: $scope.messages = { "1": [ { "content": "Hello" }, { "content": "How are you" }, { "conte ...

What is the best way to save functions that can be utilized in both Vue front-end and Node back-end environments at the same time?

As I dive into the world of Node/Express back-end and Vue.js front-end development, along with server-side rendering, I am faced with the need to create utility functions that can format textual strings. These functions need to be accessible and reusable b ...

Adjusting the height of a DIV element to suit the window dimensions

I am facing an issue with the following HTML code: <div id="subpageHeaderImageSection"> <div id="subpageHeaderLeft"> <span id="holdImageP"></span> <!--[if lte IE 10]><img id="igm" src="theImages/sub ...

Sorting elements in an array based on an 'in' condition in TypeScript

I am currently working with an arrayList that contains employee information such as employeename, grade, and designation. In my view, I have a multiselect component that returns an array of grades like [1,2,3] once we select grade1, grade2, grade3 from the ...

What is the best way to input two distinct variables into the Firebase database?

I have encountered an issue while trying to upload two variables into my Firebase database. Only the first variable, newRoute, is being successfully uploaded while new User isn't getting uploaded. The setup of the Fire configuration for the entire web ...

Struggling to save the resolved data from a promise in Node.js to a variable

I am currently utilizing nodejs to develop REST APIs and I am facing an issue with storing resolved data from multiple promises into a single variable. Here is a snippet of the code I am working with: var resultset={}; function getAllTeams() { retu ...

What steps can I take to correct my code so that it only shows a single table?

I'm facing an issue while trying to display my dynamic JSON data. It's rendering a table for each result instead of all results in the same table. My array data is coming from the backend API. const arr = [ { "Demo": [ ...

Tips for leveraging the power of Vuetify in Angular versions 7 and 9

I am looking to integrate Vuetify UI Components with Angular using VueCustomElement. While I have successfully integrated Angular and VueCustomElement, adding Vuetify has resulted in errors such as missing $attr and $. However, I am determined to add eithe ...

``How can I extract the last string in Vue.js when working with string processing?

I've been working with strings in vuejs and currently have 4 URL strings: https://web-sand.com/product/slug/apple-iphone-13 https://web-sand.com/product/slug/samsung-galaxy https://web-sand.com/product/slug/xiaomi-red https://web-sand.com/product/slug ...

"Utilizing Ramda's map function to integrate dynamic keys: A step-by-step guide

I am currently working with an array structured like this : array = ['2020-06-03', '2020-06-05', '2020-06-06'] My task is to transform it into the following format : Object { "2020-06-03": Object { "selec ...

What could be causing the delay in $q.all(promises).then() not waiting for the promises to complete?

Currently, I am tasked with utilizing AngularJS 1.5.5. My task involves making calls to multiple Rest-Services and handling the results simultaneously. $scope.callWebservices = function(){ let promises = { first: callFirstWebservice(), ...

Replacing the resetPose function in webVR

I'm currently working on a webVR project where I previously used the resetPose function to reset the origin of the scene. However, it seems that this function is now deprecated. The purpose of using it was to bring the camera back to focusing on the c ...

Issue with React container not connecting properly

I am currently facing an issue with a search bar where the input value is not displaying properly. Even when I check the value in the console, it only shows one character at a time. https://i.stack.imgur.com/Qm0Lt.png My assumption is that there might be ...

Navigating Pre-Fetched Client Routes in Gatsby with @ReachRouter

Let's consider this scenario. Imagine a user enters /company/<company-id> in the address bar. Because the app is completely separate from the backend, it must prefetch the companies. The usual flow is /login -> /company/. Handling this sequ ...