如何在注册该组件时为 vue.js 组件定义 css 样式?

新手上路,请多包涵

我可以注册一个自定义的 vue.js 组件

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

另请参阅 https://v2.vuejs.org/v2/guide/components.html

如何为我的组件包含 css 类?

我会期待类似的东西

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

但似乎没有 css 选项。

我知道我可以

a) 在全局 css 样式表中定义所有 css 类或

b) 使用 singe-file-vue-components(需要构建工具支持 *.vue 文件,参见 https://v2.vuejs.org/v2/guide/single-file-components.html

但我更愿意

c) 在注册组件时为组件指定一个css样式表。

=> 怎么做?

原文由 Stefan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 840
2 个回答

似乎没有 css 选项。

那是对的。你不能做你所描述的。 单文件组件的文档 非常清楚,其中一个优点是您可以使用它们来做到这一点,而没有它们就无法做到。

在许多 Vue 项目中,全局组件将使用 Vue.component ,然后是 new Vue({ el: '#container' }) 来定义每个页面主体中的容器元素。

这对于中小型项目非常有效,其中 JavaScript 仅用于增强某些视图。然而,在更复杂的项目中,或者当你的前端完全由 JavaScript 驱动时,这些缺点就会变得明显:

[…] 不支持 CSS 意味着虽然 HTML 和 JavaScript 被模块化为组件,但 CSS 明显被排除在外

原文由 Roy J 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是一种实现您正在寻找的东西的方法:

 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     );
        }
    }
);

原文由 Talha 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题