Search code examples
javascriptcssvue.jsstylesheetvue-component

How to define css styles for a vue.js component when registering that component?


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?


Solution

  • 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