LoginSignup
1
0

More than 3 years have passed since last update.

vueのcss-scopedとcss-moduleの違い

Last updated at Posted at 2020-10-26

この記事の対象者

vueの基礎を理解している

css-scopedのcss-moduleの共通点

両方ともコンポーネントのスタイルとして定義される

css-scoped


<template lang="html">
  <button class="button">ボタン</button>
</template>
<style lang="scss" scoped>
.button {
  // スタイル定義
}
</style>

ビルドの後のHTMLではクラス名の変化は特になし

<button data-v-015de462="" data-v-fae5bece="" type="button" class="button"> OK </button>

開発ツールでのCSSの見た目
クラス名の後ろに[data-v-015de462]が付与されている。

.button[data-v-015de462] {}

css-module


<template lang="html">
  <button :class="$style.button">ボタン</button> // $style.button という指定の仕方になる
</template>
<style lang="scss" module>
.button {
  // スタイル定義
}
</style>

ビルド後のHTMLを見るとクラス名が変化しています!!

<button data-v-fae5bece="" type="button" class="Button_button_Mvymr"> OK </button>

開発ツールでのCSSの見た目
scopedとは違い[data-XXX]は付かずビルド後に変化したクラス名が使われています!!

.Button_button_Mvymr {}

css-scopedとcss-moduleの異なる点とは

  • css-moduleの$style.buttonscript内でも使用することが可能。

公式ドキュメントから抜粋

<script>
export default {
  created () {
    console.log(this.$style.red)
    // -> "_1VyoJ-uZOjlOxP7jWUy19_0"
    // filename と className に基づいて出力された識別子。
  }
}
</script>
  • css-moduleは::v-deepでは決して上書きが決してできない

本来では下記の指定をすると子コンポーネントでscopedを指定していても::v-deepを使用するとスタイルを上書きすることが可能になりますが、css-moduleの場合は決して上書きすることができません


<style lang="scss" scoped>
::v-deep .button {
  background-color: green;
}
</style>

最後に

普段からクセでscopedを使いがちですが、今回はVSCodeの予測変換からmoduleが表示されていたので気になって調べて見ました。
css-moduleであればtemplate, script, styleから参照し合えるのでscopedより使いやすそうです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0