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:
使用 scoped 时,父组件的样式不会泄漏到子组件中组件.
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.
为了解决这个问题,你需要Deep Selector.(你可以在 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>
模板><style scoped lang="scss">.main-wrapper/deep/{@import "~bootstrap/dist/css/bootstrap.min";}</风格>
<块引用>
一些预处理器,如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 将类似于
The generated CSS would be similar to
.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.
这个解决方案是hacky.但这是我知道的唯一适用于您的用例的方法.
This solution is hacky. But it's the only way I know that can work for your use case.
这篇关于Vue 中的 Scope Bootstrap Css的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!