Scope Bootstrap Css in Vue

感情迁移 提交于 2019-12-30 03:10:11

问题


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>

But it doesn't seem like the css is scoped. Is there any way to do that?


回答1:


<style scoped src="~bootstrap/dist/css/bootstrap.css"></style>

<style scoped src="~bootstrap-vue/dist/bootstrap-vue.css"></style>

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

from the Vue doc for scoped CSS

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.

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)

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>

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.

The generated CSS would be similar to

.main-wrapper[data-v-656039f0] .modal {
    /* some css... */
}

.. which is what you want.

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.




回答2:


i wanted use vuetify in my app only on a page , and that crashed my css, then I use

 <style scoped src="vuetify/dist/vuetify.min.css"></style>

and now all works perfectly .


<template>
  <div> .......  </div>
</template>

<style scoped src="vuetify/dist/vuetify.min.css"></style>
<script> ...... </script>



回答3:


Note when reading the solution today:

The scoped attribute is deprecated and will be removed. Do not use it.

-- https://www.w3schools.com/tags/att_scoped.asp



来源:https://stackoverflow.com/questions/49653931/scope-bootstrap-css-in-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!