Skip to content

Instantly share code, notes, and snippets.

@gangsthub
Created August 21, 2019 09:04
Show Gist options
  • Save gangsthub/487bea9267eb67457db9ee5a0421962a to your computer and use it in GitHub Desktop.
Save gangsthub/487bea9267eb67457db9ee5a0421962a to your computer and use it in GitHub Desktop.
Detect if device is mobile from User Agent on Vuex
// 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