28

I am able to register a custom vue.js component with

// register
Vue.component('my-component', {
  template: '<div class="my-class">A custom component!</div>'
})   

Also see https://v2.vuejs.org/v2/guide/components.html

How can I include css classes for my component?

I would expect something like

 Vue.component('my-component', {
      template: '<div class="my-class">A custom component!</div>',
      css: '#... my css stylesheet...'
    })

but there does not seem to be a css option.

I know that I could

a) define all css classes in a global css stylesheet or

b) use singe-file-vue-components (would require build tool supporing *.vue files, see https://v2.vuejs.org/v2/guide/single-file-components.html)

but I would prefer to

c) specify a css stylesheet for the component when registering the component.

=> How to do so?

3
  • Why would you not use webpack along with vue-loader? That would allow you to import CSS in your components as well. I feel the great vue-templates that come along with Vue is what really makes Vue stand out. You basically want single-file components but not the tools that enable you to use them.
    – connexo
    Mar 1, 2018 at 16:11
  • Possible duplicate of Vue 2 component styles without Vue loader
    – sliptype
    Mar 1, 2018 at 16:13
  • 1
    @connexo - not OP, but as someone for whom Web stuff is only a minor sideline these days, the #1 thing that drew me to Vue rather than one of the zillion other frameworks was the fact that you don't need a big honking Node-based build stack to use it productively. Yes, there's a threshold of app complexity where it's probably worth biting that bullet, but it's quite a high threshold.
    – mrec
    May 21, 2019 at 17:46

6 Answers 6

13

there does not seem to be a css option.

That is correct. You cannot do what you describe. The documentation on single file components is pretty clear that one of the advantages is that you can do this with them and cannot do it without them.

In many Vue projects, global components will be defined using Vue.component, followed by new Vue({ el: '#container' }) to target a container element in the body of every page.

This can work very well for small to medium-sized projects, where JavaScript is only used to enhance certain views. In more complex projects however, or when your frontend is entirely driven by JavaScript, these disadvantages become apparent:

[...] No CSS support means that while HTML and JavaScript are modularized into components, CSS is conspicuously left out

2
  • Ok, thank you for clarification. I want to keep the number of dependencies in my project small. I am new to vue.js and I am still wondering if I want to include it at all. Now I consider two main options: #I. Also include the build tool dependencies as suggested by connexo or #II. stick to vanilla web components. The web component html files would allow to specify css classes and would not require specific build tools. However, dynamically importing those html files might become tricky.
    – Stefan
    Mar 1, 2018 at 19:10
  • I have come to this answer multiple times due to people underestimating this and moving to answers below it. Answers that suggest that component should insert css on mount will try to inser it multiple times. No Do not check if it already exist. In your application simply add a new stylesheet somewhere in component folder and include it in. Upload your css to a cdn and put it in your html file directly instead of doing any hacks below. Add style tag in document if its just related to that page and compoent. Its like any js library that comes with css for example bootstap. Nov 12, 2022 at 18:01
8

Here is a way to achieve what you're looking for:

export const ContactUs = Vue.component(
    'mycomponent-contact-us'
    ,{
        props: {
            backgroundColor: {
                type: String
                ,required: false
                ,default: "red"
            }
        }
        ,data: function(){
            return {
                
            }
        }
        ,template: `
            <div>
                <span class='contact_us_text' >Contact Us Component and its bg color will be {{backgroundColor}}</span>
            </div>
        `
        ,mounted: function(){
            var css_text = `
            .contact_us_text{
                color: `+this.backgroundColor+`;
            }
            `;
            var css = document.createElement('style');
            css.type='text/css';
            css.setAttributeNode( document.createAttribute('scopped') );
            css.appendChild(    document.createTextNode( css_text )     );
            this.$el.appendChild(   css     );
        }
    }
);
1
  • 1
    full credit goes to @smallscript above for pointing in the right direction.
    – Talha
    Apr 1, 2020 at 17:50
5

Its true that you cannot add <style> inside a Vue template or add CSS within component directly, unless you bind it or define your css globally. But you can create a custom component that will dynamically do it for you. sample

1
  • 1
    Looks like you write 50 lines of code to get a STYLE element back after VUE forced you not to do this.
    – netAction
    Nov 5, 2020 at 14:38
3

Keep in mind that Vue components are effectively macros.

Where render is the substitution function, and the vueDefinition (defn3 below) is effectively a class for the given tagName.

A template is just a convenient syntactic-sugar shorthand that will be compiled (with some vue-usage pattern restrictions) into a render function if you don't provide your own render function.

const defn3 = {
  tagName: 'ae-css',
  mounted() {
    const vueDefinition = this.$options;
    this.$el.appendChild(document.createTextNode(vueDefinition.css));
  },
  css: `
    * {
      color: blue;
    }
  `,
  render(h) {
    return h('style');
  }
}
Vue.component(defn3.tagName, defn3);

With that solution in hand, there are a number of good reasons why you probably don't want something as simplistic as what I just provided.

Namely, you want to have your css modularized such that it does not affect any aspects of your page you did not intend it to. For that, you either need carefully designed css rules with your intended inheritance and scope; probably using a class=... But a better approach would be to just use Vue's facilities that offer similar capabilities automatically.

If you want to use modern browser architecture capabilities for this, then you might want your components to be real browser DOM WebComponents that make use of the shadowDOM and keep your internal elements and styles encapsulated within a shadowRoot. See this library, for doing that in Vue.

2
  • awesome ! but can you guide who i can refer to my property in that css string. Lets say my component has a backgroundColor prop.
    – Talha
    Apr 1, 2020 at 17:39
  • Aha! figured it out. Thank you for pointing in the right direction :) defined css string in the mounted function and then used plain js to create style element, define its type as text/css and then using $el.appendChild added that style element.
    – Talha
    Apr 1, 2020 at 17:45
0

You can embed a style tag within your template root element:

Vue.component('my-component', {
      template: `
      <div class="my-class" my-component>
            A custom component!

            <style>
                  .my-class[my-component] {
                        // ... my-component styles
                  }
            </style>
      </div>
      `
})
2
  • This is not documented by the way, using a scoped style may not affect the container/parent of your style tag node Feb 3, 2020 at 20:49
  • 1
    Vue3 rejects this approach with the warning: "Template compilation error: Tags with side effect (<script> and <style>) are ignored in client component templates." :-( Feb 17, 2021 at 20:27
0

Try this:

this.$el.style.cssText = "border: 5px solid blue;"
1
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jun 15, 2022 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.