I'm trying to use a global variable in my vue template. I'm trying to use it without setting it in the data fields, because they're actually some global constants.
<template v-if="item.WheelDrive === WHEEL_DRIVE.ALLROAD">
this will give me the "Property or method is not defined on the instance but referenced during render" error.
Is it possible to direct vue not to try and bind WHEEL_DRIVE here?
You can use
computed
or even create a custommixin
to get a global value:Depending on where you are you can also use:
If you are looking for a global function:
See the following example https://jsfiddle.net/FairKing/u7y034pf/
As far as I am concerned this is not possible because:
Whenever you are using templates in vue you are also using vue template compiler in one way or another. All template expressions will be turned into render functions, and the source code that the template compiler generates looks like this:
Note the
with(this)
statement at the beginning. Every reference in the remaining function will therefore always be accessed on the instance.However, even if it was possible this would be an anti pattern:
Vue is relatively opiniated when it comes to state management. Even though you are dealing with a constant here, vue still encourages you to share global state between vue instances using vuex.
You could also just reflect your constant in your vue instance as a an attribute of your components data - I do encourage you to use vuex though if your app grows bigger.