I need to have a reactive global variable in Vue. The variable is simply a boolean that tells me whether the user is on a mobile device. I have tried so many things but this is the last thing I tried:
Vue.prototype.$testIsMobile = false
const mobileMediaMatch = window.matchMedia('(max-width: 768px)')
Vue.prototype.$testIsMobile = mobileMediaMatch.matches
window.addEventListener('resize', function () {
console.log("resizeeeee: " + mobileMediaMatch.matches)
Vue.prototype.$testIsMobile = mobileMediaMatch.matches
}, true)
Now this will get triggered when I reszie my screen because I can see the text resizeeeee getting logged repeatedly to the console. The problem is that when I use the variable $testIsMobile in other components, the variable is not reactive. It does not re-render the page accordingly until I refresh the page manually. How can I make this variable fully reactive so that any component can use it and it contains the correct value?
Here is an example of how I use it in a component:
<div>--{{$testIsMobile}}--</div>
Although there's quite a bit of overlap,
If you want to detect touch devices, I suggest isMobile (or similar). It's not reactive, because (normally) the device does not change. (e.g: if emulating - therefore changing device on the fly - you need to reload the page to reapply detection.
Vue 2 implementation:
To detect if a media matches in real time, you could roll your own, but it's already done: vue-component-media-queries (for Vue 2):
Look at the simpler syntax at the bottom.
Define as many queries as you want. They're all be available on
<MediaQuery />'sv-slot(e.g:#default="{ someQuery }")