LoginSignup
8
6

More than 3 years have passed since last update.

Nuxt.jsでデバイスによって読み込むCSSファイルを切り替える

Last updated at Posted at 2018-08-10

nuxt-device-detectというModuleを使えば実現できます。
https://github.com/nuxt-community/device-module

これを使えばコンテキストに$deviceがインジェクトされ、デバイス判別プロパティにアクセスできます。
(内部ではUser-Agentを見て切り替えている)

context.isDesktop
context.isMobile
context.isTablet
context.isMobileOrTablet

// thisからもアクセス可能
this.$device.isDesktop

あとはpageのlayoutから$deviceを使い、レイアウトを切り替えます。
layouts/pc.vueにPC用のSCSSファイルなどをstyleに読み込めばOKです。

export default {
  layout ({ app }) {
    return app.$device.isDesktop ? 'pc' : 'sp'
  }
}

全pageファイルにlayoutを記述するのは面倒だと思うので、グローバルMixinを使いましょう。
自分は以下のようなPluginを作成しました。

import Vue from 'vue'

Vue.mixin({
  layout ({ app }) {
    return app.$device.isDesktop ? 'pc' : 'sp'
  }
})
8
6
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
8
6