Using Vue.js to connect v-html to a custom CSS stylesheet

I am currently working with HTML generated by a function on an external server and I am able to preview this within a tag. Additionally, I can retrieve the CSS information in a similar manner.

<template>
   <div v-html="html"></div>
</template>

created() {
    // Fetching HTML from external server
    Axios.post(....).then((res) => {
      this.html = res.data;
    });

    // Fetching CSS file from external server
    Axios.post(....).then((res) => {
          ... apply this result to the html somehow
    });
},

The HTML content is displayed correctly but now I am looking for a way to incorporate the styles from the CSS. Is there a method that can help me achieve this?

One approach I have attempted is embedding the CSS file directly into the HTML source:

<link rel='stylesheet' type='text/css' href='css/default.css' />

However, upon doing so, I encountered the following error:

Refused to apply style from 'http://localhost:8080/css/default.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

Answer №1

If you have received css information in a format similar to html, you can implement it using the code snippet below:

const app = Vue.createApp({
  data() {
    return {
      html: '',
      css: ''
    }
  },
  computed: {
    htmlCss() {
      const result = this.html ? this.html + this.css : ''
      return result
    }
  },
  created() {
    // Make an API call
    setTimeout(() => {
      const response = `<p>rrr</p>`
      this.html = response
    }, 1000)

    // Make another API call
    setTimeout(() => {
      const response = 'p {color: red;} body {font-size: 2em;}'
      this.css = `<style>${response}</style>`
    }, 2000)
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-html="htmlCss"></div>
</div>

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

Using a Javascript array within a Bootstrap carousel allows for dynamic content to

I am looking to incorporate my javascript array into a bootstrap carousel so that the carousel can display all the elements from the array and determine which picture should be shown based on the data. I also want it to display the title, subtitle, and alt ...

Click on the input to add or remove a value

I have written a code where, on click, I insert an email address into a field. However, what I am trying to achieve is that upon the next click on the same field, it will remove the email if one already exists in the input. Below is my current code snippe ...

Node unable to interpret accented characters from CSV file input

Currently, I am utilizing npm fast-csv as my CSV reader/writer tool. It offers a simple and straightforward way to handle CSV files. My goal is to use this tool along with iconv to deal with "accented" characters and non-ASCII characters by converting them ...

Refreshing is not necessary when submitting a form using Ajax to post data

Initially, I find myself torn between using method or type, where if I define the method in the form, do I still need to define it in the ajax call? If not, why does ajax return undefined in the console? Furthermore, the code below triggers a 405 POST met ...

Error in Internet Explorer when attempting to close a Fancybox iframe that plays a YouTube video

Even the FancyApps page itself contains the error mentioned below. If you visit using Internet Explorer 9, for example, follow these steps: Go to Internet Options > Advanced > Disable script debugging (Internet Explorer). Then click on the YouTube ( ...

Sharing image using the MEAN stack

While I've found numerous resources online discussing this topic, none of them seem to present a method that resonates with me. My current setup involves a form with multiple inputs that are sent to the server upon clicking a "Submit" button. This da ...

Experiencing trouble with detecting intersections using the Three.js raycaster

After successfully writing a code to intersect some objects, I encountered an issue when adding a canvas along with other div elements in the HTML document. Now, there seems to be no intersection on the object. You can observe this live example here. If yo ...

When executed, the Node application successfully compiles

I have a TypeScript application that runs smoothly in development mode using ts-node. However, after building the application, I encounter some unexpected warnings and errors. This is my tsconfig.json: { "compilerOptions": { "incremen ...

Refreshing dynamically added rows through ajax updates

I'm struggling to clearly articulate my problem. Currently, I have a function that retrieves values from a database using ajax and then dynamically adds each result as a row in a table. This allows users to edit or delete any row as needed. I'm ...

Combining strings from an array while restricting repeated characters

I have an array of strings that need to be combined to form a single string, using a specific number referred to as the associatedNumber. This associatedNumber dictates that in the final result, all clusters of identical characters (from the array) should ...

Ensure to preselect the radio button based on the Day's value

I have set up my Radio buttons with corresponding content to be displayed when clicked. I want to automatically pre-select the tab button based on the current day. For example, if today is Sunday, the page should load showing the contents for Sunday. If i ...

Is it possible to open a PDF file in a new tab using Angular 4?

When attempting to open a PDF file using the window.open() function, I encountered an issue where the window would open and close automatically, causing the file to be downloaded rather than displayed in a new tab. Despite not having any ad blockers inst ...

Divide the sentence using unique symbols to break it into individual words, while also maintaining

Is there a way to split a sentence with special characters into words while keeping the spaces? For example: "la sílaba tónica es la penúltima".split(...regex...) to: ["la ", "sílaba ", "tónica ", "es ", "la ", "penúltima"] ↑ ...

monitoring checkbox status in vue?

When using Vue, I have created dynamic checkboxes that display as shown below: <li v-for="element in checklist" :key="element.id" class="block w-full p-1"> <div v-if="element.taskId == task" clas ...

Is setting cache: 'no-store' in a fetch request enough to mimic client-side rendering behavior in Next.js?

Currently, I am working with Next.js and utilizing the fetch method to retrieve data: const res = await fetch(`${process.env.url}/test`, { cache: 'no-store', }) My understanding is that specifying cache: 'no-store' will trigger a fre ...

Upon loading the page, trigger the controller method by utilizing the information from the query string

Can query string data be retrieved on page load with javascript? Here is how I am attempting to achieve this in my project: The view page displays tabular data. When a button is pressed, it retrieves the row's id and invokes a javascript function. ...

What is the most efficient way to retrieve the current user's ID within Loopback?

Given the instability and deprecation of loopback.getCurrentContext(), what strategies can I use to accurately identify users when they interact with API endpoints? Is it feasible to include the token ID in the request payload for verification purposes? H ...

Toggle the play/pause function by clicking - Trigger Ajax

I have a campaign that can be either played or paused. Currently, I have implemented the pause feature using AJAX and now I need to add the play feature as well. When I click on the pause button, I want it to be replaced with the play button. This is the ...

I am having trouble getting Google Maps to load

Why does the map on my website only load when the browser window is resized? Below is the JavaScript code being used: <div class="map-cont"> <div id="map" class="location-container map-padding" style="width:100%;height:400px;background:y ...

JavaScript application that features an audio player complete with a dynamic progress bar and customizable tags

Looking to create a custom audio player using HTML, CSS, and JS. The player should have basic functionality like a play button and progress bar. However, I want to allow users to add tags on the progress bar of the audio file, similar to how SoundCloud&apo ...