Home > Back-end >  Vue js v-html linked to a css stylesheet
Vue js v-html linked to a css stylesheet

Time:11-05

I have some html generated by a function on an external server and I can preview this in a tag. In a similar way I can get the css information.

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

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

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

},

The html is displayed fine but I would like to apply the styles in the css. Is there a way of doing this?

I have tried including the file in the html source:

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

but get the 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.

CodePudding user response:

If you receive css information like html , try like following snippet:

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

    // 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>

  • Related