Vue中的Scope Bootstrap CSS [英] Scope Bootstrap Css in Vue
问题描述
我正在尝试在Vue组件中使用Bootstrap,并且希望所有CSS都具有作用域.我尝试过这样的事情:
I'm trying to use Bootstrap in a Vue component, and I want all CSS to be scoped. I tried something like this:
<style scoped>
@import "~bootstrap/dist/css/bootstrap.css";
@import "~bootstrap-vue/dist/bootstrap-vue.css";
</style>
但是css似乎没有作用域.有什么办法吗?
But it doesn't seem like the css is scoped. Is there any way to do that?
推荐答案
<style scoped src="~bootstrap/dist/css/bootstrap.css"></style>
<style scoped src="~bootstrap-vue/dist/bootstrap-vue.css"></style>
更新:使用SCSS的黑客行为
Update: a hack using SCSS
第一个解决方案不起作用的原因:
Reason why the first solution won't work:
在范围内,父组件的样式不会泄漏到子组件中 组件.
With scoped, the parent component's styles will not leak into child components.
如果您希望作用域样式中的选择器为深度",即影响 子组件,您可以使用>>>组合器
If you want a selector in scoped styles to be "deep", i.e. affecting child components, you can use the >>> combinator
您提到的模态显然不受导入引导程序的组件的控制.也许这是一个子组件.也许您正在使用Bootstrap模态的jquery版本.无论哪种方式,数据属性都不会添加到模式中.
The modal you mentioned is apparently not being controlled by the component where you imported bootstrap. Perhaps it's a child component. Perhaps you're using the jquery version of Bootstrap modal. Either way, the data attributes won't be added to the modal.
为了解决这个问题,您需要深度选择器. (您可以在 https://vue-loader中详细了解.vuejs.org/en/features/scoped-css.html )
In order to solve this, you need Deep Selector. (you may read about it in more detail in https://vue-loader.vuejs.org/en/features/scoped-css.html)
这是我将使用SCSS导入整个Bootstrap CSS的方法. (我认为仅使用纯CSS是不可能的.)
Here's how I would import the entire Bootstrap CSS using SCSS. (I think it's impossible to do this using pure CSS only.)
<template>
<div class="main-wrapper">
/* ... */
</div>
</template>
<style scoped lang="scss">
.main-wrapper /deep/ {
@import "~bootstrap/dist/css/bootstrap.min";
}
</style>
某些预处理器,例如Sass,可能无法解析>>> 适当地.在这种情况下,您可以改用/deep/组合器- 它是>>>的别名,并且工作原理完全相同.
Some pre-processors, such as Sass, may not be able to parse >>> properly. In those cases you can use the /deep/ combinator instead - it's an alias for >>> and works exactly the same.
生成的CSS类似于
.main-wrapper[data-v-656039f0] .modal {
/* some css... */
}
..这就是您想要的.
.. which is what you want.
但是,我得说,导入整个Bootstrap CSS是一个非常糟糕的做法.尝试仅从 bootstrap- sass .
BUT, I gotta say, importing the entire Bootstrap CSS is a really bad practice. Try to import only and exactly what you are going to use from bootstrap-sass instead.
此解决方案存在漏洞.但这是我所知道的唯一适用于您的用例的方法.
This solution is hacky. But it's the only way I know that can work for your use case.
这篇关于Vue中的Scope Bootstrap CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!