くらげになりたい。

くらげのようにふわふわ生きたい日曜プログラマなブログ。趣味の備忘録です。

Nuxt.jsでユーザエージェントを判定してくれるnuxt-user-agent

Nuxt.jsでOSやブラウザごとに挙動を変えたいなと思い、
いろいろ調べていたらユーザエージェントをいい感じに判定できるやつが!
nuxt-user-agentを調べたときの備忘録

準備する

インストール

$ npm i -S nuxt-user-agent

nuxt.config.jsの設定

const config: NuxtConfiguration = {
  modules: [
    'nuxt-user-agent',
  ]
}

使ってみる

asyncData内で

asyncData(context) {
  const deviceType = context.$ua.deviceType()
  return { deviceType }
}

methods/created/mountedとかで

methods: {
  something() {
    const deviceType = this.$ua.deviceType()
    this.deviceType = deviceType
  }
}

Storeのactionsで

actions: {
  getDeviceType ({ commit }) {
    const deviceType = this.$ua.deviceType()
    commit('SET_DEVICE_TYPE', deviceType)
  }
}

templateで

<template>
  <section>
    <div v-if="$ua.isFromPc()">
      <span>PC</span>
    </div>
    <div v-if="$ua.isFromSmartphone()">
      <span>Smartphone</span>
    </div>
    <div v-if="$ua.isFromMobilephone()">
      <span>Mobilephone</span>
    </div>
    <div v-if="$ua.isFromTablet()">
      <span>Tablet</span>
    </div>
    <div v-if="$ua.isFromAppliance()">
      <span>Appliance</span>
    </div>
    <div v-if="$ua.isFromCrawler()">
      <span>Crawler</span>
    </div>
  </section>
</template>

できること

README.mdより

method type example
deviceType string pc
os string Mac OSX
osVersion string 10.12.6
browser string Chrome
browserVersion string 65.0.3325.181
browserVendor string Google
isFromIphone boolean true
isFromIpad boolean true
isFromIpod boolean true
isFromIos boolean true
isFromAndroidMobile boolean true
isFromAndroidTablet boolean true
isFromAndroidOs boolean true
isFromWindowsPhone boolean true
isFromPc boolean true
isFromSmartphone boolean true
isFromMobilephone boolean true
isFromAppliance boolean true
isFromCrawler boolean true
isFromTablet boolean true

なんと便利な( ゚д゚)! 以上!!

参考にしたサイト様