LoginSignup
5
8

More than 3 years have passed since last update.

Nuxt.js の layouts で style に scoped を指定しないとグローバルになる

Last updated at Posted at 2018-05-30

Nuxt.js の layouts ディレクトリでのレイアウト指定

pages ディレクトリに設置したファイルに laytout プロパティを指定することで
指定するレイアウトを切り替えることが可能となるが・・・

layouts/default.vue
<template lang="pug">
  div
    nuxt
</template>

<style lang="scss">
// sass-loader などを入れているとする
body: {
  color: white;
}
</style>

上記は pug や sass-loader などをインストールしておくことにより
Pug, scss が使用可能なものとします

pages/index.vue
<template lang="pug">
  div ホーム
</template>

<script>
export default {
  // layout を指定しなければ layouts/default.vue が使用される
};

複数の layout を定義しそれぞれに style を定義

下記のような複数種類の layouts, pages を用意することにより
page ごとに layout を切り替える実装をする

赤組

layouts/red.vue
<template lang="pug">
  div layout red
    nuxt
</template>

<style lang="scss">
body {
  background-color: red;
}
</style>
pages/red.vue
<template lang="pug">
  div Red
</template>

<script>
export default {
  // layouts/red.vue を指定
  layout: 'red',
};
</script>

青組

layouts/blue.vue
<template lang="pug">
  div layout blue
    nuxt
</template>

<style lang="scss">
body {
  background-color: blue;
}
</style>
pages/blue.vue
<template lang="pug">
  div Blue
</template>

<script>
export default {
  // layouts/blue.vue を指定
  layout: 'blue',
};
</script>

結果、赤組の勝ち

result.jpg

layouts に存在するもののうち
scoped 指定のないスタイルはプロジェクト単位で影響する模様

こちらは pages/red.vue で layouts/red.vue をやめても
pages で使用されていないからと言って読み込まれないわけではないようです

pages/red.vue
<template lang="pug">
  div Red
</template>

<script>
export default {
  // 指定を解除し layouts/default.vue を使用
  //layout: 'red',
};
</script>

結論としては style には layouts 配下でも scoped をつけましょう

というかデフォルトで scoped 扱いのほうがよいのでは・・・

5
8
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
5
8