Ste*_*fan 6 javascript css stylesheet vue.js vue-component
我可以使用注册一个自定义的vue.js组件
// register
Vue.component('my-component', {
template: '<div class="my-class">A custom component!</div>'
})
Run Code Online (Sandbox Code Playgroud)
另请参阅https://vuejs.org/v2/guide/components.html
如何为我的组件包括CSS类?
我希望有类似的东西
Vue.component('my-component', {
template: '<div class="my-class">A custom component!</div>',
css: '#... my css stylesheet...'
})
Run Code Online (Sandbox Code Playgroud)
但似乎没有css选择。
我知道我可以
a)在全局CSS样式表中定义所有CSS类,或
b)使用singe-file-vue-components(将需要构建工具支持* .vue文件,请参阅https://vuejs.org/v2/guide/single-file-components.html)
但我宁愿
c)在注册组件时为该组件指定一个css样式表。
=>怎么做?
Roy*_*y J 12
似乎没有 css 选项。
那是正确的。你不能做你所描述的。关于单文件组件的文档非常清楚,优点之一是您可以使用它们来完成此操作,而没有它们则无法完成。
在许多 Vue 项目中,全局组件将使用 定义
Vue.component,然后new Vue({ el: '#container' })在每个页面的正文中定位一个容器元素。这对于中小型项目非常有效,其中 JavaScript 仅用于增强某些视图。然而,在更复杂的项目中,或者当你的前端完全由 JavaScript 驱动时,这些缺点变得明显:
[...] 不支持 CSS意味着虽然 HTML 和 JavaScript 被模块化为组件,但 CSS 明显被排除在外
小智 8
这是实现您正在寻找的目标的一种方法:
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 );
}
}
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11066 次 |
| 最近记录: |