user10090131
user10090131

Reputation:

How to dynamically inject styles in Nuxt?

Whilst building a Nuxt application with WordPresss, I'm importing custom css from the WordPress API.

How do I inject custom CSS into a template?

<template>
  <div class="container">
    <style>
      {{ content.custom_css }} 
    </style>
    <div class="wordvue mt-5" v-html="content.rendered"></div>
  </div>
</template>

My problem is that this is working in development mode, but the style tag is removed in production mode.

Is there any solution to this ?

Upvotes: 0

Views: 2640

Answers (1)

Djurdjen
Djurdjen

Reputation: 283

<style> tags are automaticly stripped when compiling. Luckily tmorehouse offers a solution by using Vue's <component>

<template>
  <div>
    <component is="style">
      .foo[data-id="{{ uniqueId }}"] {
        color: {{ color }};
      }
      .foo[data-id="{{ uniqueId }}"] .bar {
        text-align: {{ align }}
      }
    </component>
    <div class="foo" :id="id" :data-id="uniqueId">
      <div class="bar">
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    id: {
      type: String,
      default: null
    }
  },
  computed: {
    uniqueId() {
      // Note: this._uid is not considered SSR safe though, so you
      // may want to use some other ID/UUID generator that will
      // generate the same ID server side and client side. Or just
      // ensure you always provide a unique ID to the `id` prop
      return this.id || this._uid;
    },
    color() {
      return someCondition ? 'red' : '#000';
    },
    align() {
      return someCondition ? 'left' : 'right';
    }
  }
}
</script>

Check https://forum.vuejs.org/t/about-using-style-tags-inside-templates/7275/3 for more info

Upvotes: 1

Related Questions