LoginSignup
6
5

More than 5 years have passed since last update.

nuxt-user-agentを使ってUser-Agentを判定する

Last updated at Posted at 2019-02-11

実際にNuxt.jsでUser-Agentを判定したいことがあると思いますが、今回nuxt-user-agentを使ってみてすごい使いやすかったので手順などを書こうと思いました。

手順

まずモジュールのインストールからです。

yarn add nuxt-user-agent
or
npm install nuxt-user-agent

でインストールをします。

次にnuxt.config.jsのセットアップです。
modules部分にnuxt-user-agentを追加します。

nuxt.config.js
modules: [
  'nuxt-user-agent',
]

これでセットアップは完了です。

次に実際に使ってみます。

asyncData

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

method

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

store

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

template

<template>
  <div id="wrap">
    <div 
      v-if="$ua.deviceType() === 'pc'" 
      class="pc">PCです</div>
    <div 
      v-else-if="$ua.deviceType() === 'tablet'" 
      class="pc">TABLETです</div>
    <div 
      v-else-if="$ua.deviceType() === 'smartphone'" 
      class="pc">SPです</div>
  </div>
</template>

のような形で使用します。

また判定できる種類はこちらに載っています。

実際にnuxt-user-agentを使ってみましたが、かなり使いやすくまた判定できる種類が多いのですごいよかったです。個人的にUser-Agentの判定はmiddleware周りでやるよりもnuxt-user-agentを使ってUser-Agent判定した方がいいかなと思いました。

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