如何在注册该组件时为vue.js组件定义css样式? [英] How to define css styles for a vue.js component when registering that component?

查看:244
本文介绍了如何在注册该组件时为vue.js组件定义css样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够注册一个自定义的vue.js组件

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

另见 https://vuejs.org/v2/guide/components.html

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

How can I include css classes for my component?

我希望类似

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

但似乎没有 css 选项。

我知道我可以

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

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

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

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

但我更愿意

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

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

=>怎么办?

推荐答案


似乎没有css选项。

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.


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

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.

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

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:

[...]
没有CSS支持意味着虽然HTML和JavaScript是
模块化为组件,但CSS显然被忽略了

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

这篇关于如何在注册该组件时为vue.js组件定义css样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆