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

若如初见. 提交于 2019-12-05 07:18:50

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!