Vue
Vueでスマホやアンドロイドかどうかを判別する方法
いつもご利用ありがとうございます。このブログは、広告費によって運営されています。
オススメ本
Vue でスマホやアンドロイドかどうかを判別する方法についてまとめました。
結論
export default {
methods: {
test() {
if (this.isMobile()) {
console.log("スマホ");
} else {
console.log("スマホ以外");
}
},
isMobile() {
var userAgent = window.navigator.userAgent.toLowerCase();
if (
userAgent.indexOf("iphone") != -1 ||
userAgent.indexOf("ipad") != -1 ||
userAgent.indexOf("android") != -1 ||
userAgent.indexOf("mobile") != -1
) {
return true;
} else {
return false;
}
},
},
};
デバイスの判別は、userAgent の項目をみる
isMobile() {
var userAgent = window.navigator.userAgent.toLowerCase
console.log(userAgent)
}
このようにコンソールで確認すると、文字列でどのユーザーエージェントを使っているのか確認することができます。
それに対して、
indexOf を使って「この文字列が使われているか」でスマホかどうかを判別してみました。
パッケージの導入も選択肢のひとつ
Nuxt で、「パソコン」と「スマホ」を判別したいだけなら以下のパッケージがオススメ
Nuxt でもう少し細かくデバイスを分岐させたい
JavaScript でも同様に判別が可能
Vue だけでなく、JavaScript でも同様に
var userAgent = window.navigator.userAgent.toLowerCase();
で取得できます。
まとめ
以上です。
誰かの参考になればと思います。
苦情、誤りに関する指摘は下の Twitter の DM から頂ければ幸いです。
それでは!