Created
August 21, 2019 09:04
-
-
Save paulmelero/487bea9267eb67457db9ee5a0421962a to your computer and use it in GitHub Desktop.
Detect if device is mobile from User Agent on Vuex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See https://github.com/nuxt-community/device-module | |
const mutationTypes = { | |
CHANGE_MOBILE: 'CHANGE_MOBILE', | |
} | |
const checkIfMobileOnServerSide = ({ req, isServer }) => { | |
if (isServer) return false | |
const userAgent = req && req.headers['user-agent'] | |
const isMobile = /mobile/i.test(('' + userAgent).toLowerCase()) | |
return isMobile | |
} | |
export const state = () => ({ | |
isMobile: false, | |
}) | |
export const getters = { | |
isMobile: state => state.isMobile, | |
} | |
export const mutations = { | |
[mutationTypes.CHANGE_MOBILE](state, isMobile) { | |
state.isMobile = isMobile | |
}, | |
} | |
export const actions = { | |
// https://nuxtjs.org/guide/vuex-store/#the-nuxtserverinit-action | |
nuxtServerInit({ commit }, context) { | |
commit(mutationTypes.CHANGE_MOBILE, checkIfMobileOnServerSide(context)) | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment