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>