WEB开发

在vue项目中使用css module实现css的模块化编程

2018-11-28  本文已影响0人  情有千千节

CSS模块化,module替代scoped

vue-loader中对于scoped以及module的介绍
参考博文

# 引入配置 webpack.bash.config.js
# module>rules

{
    test: /\.scss$/,
    // loaders: ['style', 'css', 'scss']
    use: [
        'vue-style-loader',
        {
            loader: 'css-loader',
            options: { modules: true }
        },
        'sass-loader'
    ]
}

项目中的应用

<style module>

在模板中使用动态类绑定:class,并在类名前面加上'$style.'

<template>
  <p :class="$style.red">
    This should be red
  </p>
</template>
## 如果类名包含中划线,则使用中括号语法
<h4 :class="$style['header-tit']">类别推荐</h4>

如果需要将一些提升到全局 可以使用:global

:global {
  .vux-swiper, .weui-dialog {
    overflow: visible!important;
  }
  .item {
    border: 1px solid #ececec;
    padding: 5px 15px;
    font-size: 16px;
  }
  .item-selected {
    border: 1px solid $m_pink;
    color: $m_pink;
  }
  .fade-enter-active, .fade-leave-active {
    transition: opacity .2s;
  }
  .fade-enter, .fade-leave-to {
    opacity: 0;
  }
}

判断父组件是否传来样式,没有的话使用默认的

<div :class="btnStyle" @click="login">{{btnMsg}}</div>
props: {
 btnStyle: {
      type: String,
      default: function () {
        return this.$style.loginBtn
      }
   }

绑定多个

<x-icon type="ios-arrow-back" :class="[$style.icon, leftStyle]" @click="back"></x-icon>

动态绑定class部分

<swiper auto loop height="146px" :class="$style.swiper" @on-index-change="activeIndex">
          <swiper-item :class="[$style['swiper-item'],{[$style.active]:(active === index)}]" v-for="(item,index) in carouselfigs" :key="index">
            <img :class="$style.img" :src="item.banner" :alt="item.title" @click="link(item.banner_href)">
          </swiper-item>
        </swiper>

<!--react中-->
className={`swiper-container ${style['banner-h']}`}
上一篇 下一篇

猜你喜欢

热点阅读